<?php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// Ensure DB config exists
if (!file_exists('config/db.php')) {
    die("Error: config/db.php not found.");
}
require 'config/db.php';

$error = "";
$msg = isset($_GET['msg']) ? $_GET['msg'] : "";

// 1. HANDLE LOGIN SUBMISSION
if (isset($_POST['login'])) {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    // Fetch User
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user) {
        // 2. CHECK PASSWORD
        if (password_verify($password, $user['password_hash'])) {
            
            // 3. SET SESSION VARIABLES
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['reseller_status'] = $user['reseller_status'] ?? 'none';
            
            // Load Permissions if staff (for admin panel checks)
            $_SESSION['permissions'] = $user['permissions'] ?? '[]';

            // Log the login (if logger exists)
            if (file_exists('includes/functions.php')) {
                require_once 'includes/functions.php';
                if (function_exists('logActivity')) {
                    logActivity("User Login", "Logged in: " . $email);
                }
            }

            // 4. SMART REDIRECT
            if ($user['role'] === 'admin' || $user['role'] === 'staff') {
                header("Location: admin/index.php");
            } else {
                if (isset($_SESSION['redirect_url'])) {
                    $go_to = $_SESSION['redirect_url'];
                    unset($_SESSION['redirect_url']);
                    header("Location: " . $go_to);
                } else {
                    header("Location: profile.php");
                }
            }
            exit();
        } else {
            $error = "Invalid password.";
        }
    } else {
        $error = "No account found with that email.";
    }
}

// Include Header (Check if file exists first)
if (file_exists('includes/header.php')) {
    include 'includes/header.php'; 
} else {
    // Fallback simple header if include is missing, to prevent white screen
    echo '<!DOCTYPE html><html><head><title>Login</title></head><body>';
}
?>

<!-- 3D LOGIN STYLES -->
<style>
    /* Full Screen Gradient Background */
    .login-wrapper {
        background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); /* Deep Blue 3D Gradient */
        min-height: 80vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
    }

    /* The 3D Card */
    .login-card {
        background: rgba(255, 255, 255, 0.95);
        width: 100%;
        max-width: 400px;
        padding: 40px;
        border-radius: 20px;
        text-align: center;
        
        /* 3D Deep Shadow */
        box-shadow: 
            0 20px 50px rgba(0,0,0,0.3), 
            0 0 0 1px rgba(255,255,255,0.5) inset;
        
        transform: translateY(0);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }

    .login-card:hover {
        transform: translateY(-5px); /* Floating effect */
        box-shadow: 0 30px 60px rgba(0,0,0,0.4);
    }

    .login-card h2 {
        color: #333;
        margin-bottom: 30px;
        font-weight: 800;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    /* Inputs */
    .input-group {
        text-align: left;
        margin-bottom: 20px;
    }
    .input-label {
        font-size: 13px;
        color: #666;
        font-weight: bold;
        margin-bottom: 5px;
        display: block;
    }
    .styled-input {
        width: 100%;
        padding: 12px;
        border: 2px solid #eee;
        border-radius: 8px;
        font-size: 16px;
        box-sizing: border-box;
        transition: border-color 0.3s;
    }
    .styled-input:focus {
        border-color: #2a5298;
        outline: none;
    }

    /* Button */
    .btn-3d {
        width: 100%;
        padding: 14px;
        background: linear-gradient(to right, #1e3c72, #2a5298);
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        transition: transform 0.2s;
        box-shadow: 0 5px 15px rgba(30, 60, 114, 0.3);
    }
    .btn-3d:hover {
        transform: scale(1.02);
    }
    
    /* Google Button Style */
    .btn-google {
        background: #db4437; 
        color: white; 
        width: 100%; 
        display: block; 
        text-align: center; 
        padding: 12px; 
        border-radius: 8px; 
        font-weight: bold; 
        margin-bottom: 20px; 
        text-decoration: none;
        box-shadow: 0 4px 10px rgba(219, 68, 55, 0.3);
        transition: transform 0.2s;
        box-sizing: border-box;
    }
    .btn-google:hover { transform: translateY(-2px); }

    /* Links */
    .auth-links { margin-top: 25px; font-size: 14px; color: #666; }
    .auth-links a { color: #2a5298; text-decoration: none; font-weight: bold; }
    .auth-links a:hover { text-decoration: underline; }
</style>

<div class="login-wrapper">
    <div class="login-card">
        <h2>Member Login</h2>
        
        <?php if($error): ?>
            <div style="background:#ffdddd; color:#c0392b; padding:10px; border-radius:5px; margin-bottom:20px;">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>
        
        <?php if($msg == 'verified'): ?>
            <div style="background:#d4edda; color:#155724; padding:10px; border-radius:5px; margin-bottom:20px;">
                Email Verified! You can now login.
            </div>
        <?php endif; ?>

        <!-- Google Login Button -->
        <?php 
        $google_config_path = 'config/google_config.php';
        if(file_exists($google_config_path)) {
            include $google_config_path; 
            // Ensure constants are defined before using
            if(defined('GOOGLE_CLIENT_ID') && defined('GOOGLE_REDIRECT_URL')) {
                $login_url = "https://accounts.google.com/o/oauth2/auth?scope=" . urlencode("email profile") . "&redirect_uri=" . urlencode(GOOGLE_REDIRECT_URL) . "&response_type=code&client_id=" . GOOGLE_CLIENT_ID . "&access_type=online";
            ?>
            <a href="<?php echo $login_url; ?>" class="btn-google">
                <i class="fab fa-google"></i> Continue with Google
            </a>
            <div style="position: relative; margin: 20px 0; text-align: center;">
                <hr style="border: 0; border-top: 1px solid #eee;">
                <span style="background: #fff; padding: 0 10px; color: #aaa; font-size: 12px; position: absolute; top: -10px; left: 50%; transform: translateX(-50%);">OR</span>
            </div>
            <?php } 
        } ?>

        <form method="POST">
            <div class="input-group">
                <label class="input-label">Email Address</label>
                <input type="email" name="email" class="styled-input" placeholder="name@example.com" required>
            </div>

            <div class="input-group">
                <label class="input-label">Password</label>
                <input type="password" name="password" class="styled-input" placeholder="Enter password" required>
            </div>

            <button type="submit" name="login" class="btn-3d">LOGIN SECURELY</button>
        </form>

        <div class="auth-links">
            <a href="forgot_password.php">Forgot Password?</a>
            <br><br>
            Don't have an account? <a href="register.php">Register Here</a>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>