<?php
session_start();
require_once 'config.php';

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: user_dashboard.php");
    exit;
}

$error = '';

$redirect_qs = '';
if (!empty($_GET['redirect'])) {
    $requested = basename($_GET['redirect']);
    if (preg_match('/^[a-zA-Z0-9_\-]+\.php$/', $requested)) {
        $redirect_qs = '?redirect=' . urlencode($requested);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'] ?? '';

    if (empty($email) || empty($password)) {
        $error = "Please enter both email and password.";
    } else {
        // Verify reCAPTCHA
        $recaptcha_response = $_POST['g-recaptcha-response'] ?? '';
        $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = [
            'secret' => RECAPTCHA_SECRET_KEY,
            'response' => $recaptcha_response
        ];
        $options = [
            'http' => [
                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query($data)
            ]
        ];
        $context = stream_context_create($options);
        $verify_result = file_get_contents($verify_url, false, $context);
        $captcha_success = json_decode($verify_result);

        if (!$captcha_success->success) {
            $error = "Please verify you are not a robot.";
        } else {
            $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }

            // Check Users Table
            $stmt = $conn->prepare("SELECT id, org_name, password, role, is_verified, IFNULL(is_active, 1) as is_active FROM users WHERE email = ?");
            if (!$stmt) {
                $error = "A system error occurred. Please try again later.";
                $conn->close();
            } else {
                $stmt->bind_param("s", $email);
                $stmt->execute();
                $res = $stmt->get_result();

                if ($user = $res->fetch_assoc()) {
                    if ($user['is_active'] == 0) {
                        $error = "Your account has been suspended. Please contact support.";
                    } else if (password_verify($password, $user['password'])) {
                        session_regenerate_id(true);

                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['user_name'] = $user['org_name'];
                        $_SESSION['user_email'] = $email;
                        $_SESSION['user_role'] = $user['role'] ?? 'user';

                        if ($user['role'] === 'admin') {
                            $_SESSION['admin_logged_in'] = true;
                        }

                        $redirect = 'user_dashboard.php';
                        if (!empty($_GET['redirect'])) {
                            $requested = basename($_GET['redirect']);
                            if (preg_match('/^[a-zA-Z0-9_\-]+\.php$/', $requested)) {
                                $redirect = $requested;
                            }
                        }
                        header("Location: " . $redirect);
                        exit;
                    } else {
                        $error = "Invalid password.";
                    }
                } else {
                    $error = "No account found with that email.";
                }
                $stmt->close();
                $conn->close();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - SaniBook</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <!-- FontAwesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
        body {
            font-family: 'Outfit', sans-serif;
            background-color: #f8fafc;
            background-image: radial-gradient(#e2e8f0 1px, transparent 1px);
            background-size: 24px 24px;
        }

        .login-card {
            background: white;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            transition: all 0.3s ease;
        }

        .login-card:hover {
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        }
    </style>
</head>

<body class="min-h-screen flex items-center justify-center p-4">

    <!-- Back Button -->
    <a href="index.php"
        class="absolute top-6 left-6 text-slate-500 hover:text-blue-600 font-medium flex items-center gap-2 transition-colors">
        <i class="fa-solid fa-arrow-left"></i> Home
    </a>

    <div class="login-card w-full max-w-md bg-white rounded-2xl overflow-hidden border border-slate-100">

        <!-- Header -->
        <div class="bg-blue-900 p-8 text-center relative overflow-hidden">
            <div class="absolute inset-0 bg-gradient-to-br from-blue-800 to-blue-950 opacity-90"></div>
            <div class="absolute -bottom-10 -right-10 w-40 h-40 bg-blue-500 rounded-full blur-3xl opacity-20"></div>

            <div class="relative z-10">
                <a href="index.php" class="inline-block mb-2">
                    <img src="images/saniBook logo.png" alt="SaniBook"
                        class="h-12 w-auto bg-white/10 p-1 rounded-lg backdrop-blur-sm">
                </a>
                <h2 class="text-2xl font-bold text-white tracking-tight">Welcome Back</h2>
                <p class="text-blue-200 text-sm mt-1">Sign in to access your dashboard</p>
            </div>
        </div>

        <!-- Form -->
        <div class="p-8">
            <?php if ($error): ?>
                <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded text-sm flex items-start">
                    <i class="fa-solid fa-circle-exclamation mt-0.5 mr-2"></i>
                    <div><?php echo $error; ?></div>
                </div>
            <?php endif; ?>

            <?php if (!empty($_GET['redirect']) && basename($_GET['redirect']) === 'submit-data.php'): ?>
                <div class="bg-blue-50 border-l-4 border-blue-500 text-blue-700 p-4 mb-6 rounded text-sm flex items-start">
                    <i class="fa-solid fa-circle-info mt-0.5 mr-2"></i>
                    <div>
                        Please sign in to submit your data.
                    </div>
                </div>
            <?php endif; ?>

            <form method="POST" action="" class="space-y-5">
                <div>
                    <label for="email" class="block text-sm font-semibold text-slate-700 mb-1">Email Address</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fa-regular fa-envelope text-slate-400"></i>
                        </div>
                        <input type="email" id="email" name="email" required
                            class="w-full pl-10 pr-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none text-slate-800 transition-all"
                            placeholder="name@organization.com">
                    </div>
                </div>

                <div>
                    <label for="password" class="block text-sm font-semibold text-slate-700 mb-1">
                        Password
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fa-solid fa-lock text-slate-400"></i>
                        </div>
                        <input type="password" id="password" name="password" required
                            class="w-full pl-10 pr-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none text-slate-800 transition-all"
                            placeholder="••••••••">
                    </div>
                    <div class="text-right mt-1">
                        <a href="forgot-password.php" class="text-xs text-blue-600 hover:text-blue-800">Forgot
                            password?</a>
                    </div>
                </div>

                <div>
                    <!-- Recaptcha -->
                    <div class="g-recaptcha" data-sitekey="<?= RECAPTCHA_SITE_KEY ?>"></div>
                </div>

                <button type="submit"
                    class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-4 rounded-lg shadow-md transition-all transform hover:-translate-y-0.5 flex items-center justify-center gap-2">
                    Sign In
                </button>
            </form>

            <?php if (defined('GOOGLE_OAUTH_ENABLED') && GOOGLE_OAUTH_ENABLED): ?>
                <div class="relative my-6">
                    <div class="absolute inset-0 flex items-center">
                        <div class="w-full border-t border-slate-200"></div>
                    </div>
                    <div class="relative flex justify-center text-xs"><span
                            class="bg-white px-3 text-slate-400 uppercase tracking-wider">or</span></div>
                </div>
                <a href="auth/google-login.php"
                    class="w-full flex items-center justify-center gap-3 py-2.5 px-4 border border-slate-300 rounded-lg hover:bg-slate-50 transition-all text-slate-700 font-medium text-sm">
                    <svg width="20" height="20" viewBox="0 0 48 48">
                        <path fill="#EA4335"
                            d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z" />
                        <path fill="#4285F4"
                            d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z" />
                        <path fill="#FBBC05"
                            d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z" />
                        <path fill="#34A853"
                            d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z" />
                    </svg>
                    Sign in with Google
                </a>
            <?php endif; ?>

            <div class="mt-8 text-center border-t border-slate-100 pt-6">
                <p class="text-sm text-slate-500">
                    Don't have an account?
                    <a href="signup.php<?php echo $redirect_qs; ?>"
                        class="text-blue-600 font-semibold hover:text-blue-800">Create one</a>
                </p>
                <div class="mt-4">
                    <a href="admin/login.php"
                        class="text-xs text-slate-400 hover:text-slate-600 flex items-center justify-center gap-1">
                        <i class="fa-solid fa-shield-halved"></i> Admin Login
                    </a>
                </div>
            </div>
        </div>
    </div>

</body>

</html>