<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

if (!file_exists('config/db.php')) {
    die("Error: config/db.php not found.");
}
require 'config/db.php';

$error = "";
$msg = isset($_GET['msg']) ? $_GET['msg'] : "";

if (isset($_POST['login'])) {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user) {
        if (password_verify($password, $user['password_hash'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['reseller_status'] = $user['reseller_status'] ?? 'none';
            $_SESSION['permissions'] = $user['permissions'] ?? '[]';

            if (file_exists('includes/functions.php')) {
                require_once 'includes/functions.php';
                if (function_exists('logActivity')) {
                    logActivity("User Login", "Logged in: " . $email);
                }
            }

            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.";
    }
}

if (file_exists('includes/header.php')) {
    include 'includes/header.php';
} else {
    echo '<!DOCTYPE html><html><head><title>Login</title></head><body>';
}
?>

<div class="auth-page">
    <div class="auth-card">
        <h2>Welcome Back</h2>
        <p class="subtitle">Login to access your dashboard, orders & wallet.</p>

        <?php if($error): ?>
            <div class="alert alert-error" style="margin-bottom: 20px;">
                <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <?php if($msg == 'verified'): ?>
            <div class="alert alert-success" style="margin-bottom: 20px;">
                <i class="fas fa-check-circle"></i> Email Verified! You can now login.
            </div>
        <?php endif; ?>

        <?php
        $google_config_path = 'config/google_config.php';
        if(file_exists($google_config_path)) {
            include $google_config_path;
            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 btn-secondary" style="width:100%; margin-bottom: 16px;">
            <i class="fab fa-google" style="color: #db4437;"></i> Continue with Google
        </a>
        <div class="divider">or</div>
        <?php }
        } ?>

        <form method="POST">
            <div class="form-group">
                <label>Email Address</label>
                <input type="email" name="email" class="form-control" placeholder="name@example.com" required>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" placeholder="Enter your password" required>
            </div>
            <button type="submit" name="login" class="btn btn-primary" style="width:100%;">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'; ?>
