<?php
/**
 * User Login Page
 * Location: public_html/login.php
 */

require_once __DIR__ . '/connections/connect.php';
require_once __DIR__ . '/includes/functions.php';

// Redirect if already logged in
if (is_logged_in()) {
    header("Location: team/dashboard.php");
    exit;
}

$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
    $password = $_POST['password'] ?? '';
    $remember_me = isset($_POST['remember']);

    if (!$email || empty($password)) {
        $error_msg = "Please enter both email address and password.";
    } else {
        // Fetch user record
        $stmt = $pdo->prepare("SELECT u.*, a.company_name FROM users u JOIN accounts a ON u.account_id = a.id WHERE u.email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password_hash'])) {
            if (!$user['is_verified']) {
                $error_msg = "Your email address has not been verified yet. Please check your inbox.";
            } else {
                // Set Session Variables
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['account_id'] = $user['account_id'];
                $_SESSION['first_name'] = $user['first_name'];
                $_SESSION['last_name'] = $user['last_name'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['company_name'] = $user['company_name'];

                // Optional Remember Me Cookie (30 days)
                if ($remember_me) {
                    setcookie('remember_user', $user['id'], time() + (86400 * 30), "/");
                }

                header("Location: team/dashboard.php");
                exit;
            }
        } else {
            $error_msg = "Invalid email address or password.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - MiBuildqc</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
        body { font-family: 'Plus Jakarta Sans', sans-serif; }
    </style>
</head>
<body class="bg-slate-100 min-h-screen flex items-center justify-center p-4">

    <div class="bg-white rounded-[24px] max-w-[420px] w-full p-8 shadow-xl border border-slate-100 space-y-6">
        
        <!-- Header Banner Logo -->
        <div class="bg-slate-900 rounded-xl py-3.5 px-6 text-center shadow-xs">
            <span class="text-3xl font-extrabold text-white tracking-tight">
                MiBuild<span class="text-indigo-300">qc</span>
            </span>
        </div>

        <!-- Page Title -->
        <h1 class="text-2xl font-bold text-center text-[#3D3836]">Login</h1>

        <!-- Error Message -->
        <?php if (!empty($error_msg)): ?>
            <div class="p-3.5 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs text-center">
                <?php echo htmlspecialchars($error_msg); ?>
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['error'])): ?>
            <div class="p-3.5 rounded-xl bg-amber-50 border border-amber-200 text-amber-900 text-xs text-center">
                <?php echo htmlspecialchars($_GET['error']); ?>
            </div>
        <?php endif; ?>

        <!-- Login Form -->
        <form action="login.php" method="POST" class="space-y-4">
            
            <div>
                <label class="block text-xs font-semibold text-slate-500 mb-1">Email Address</label>
                <input 
                    type="email" 
                    name="email" 
                    required 
                    value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" 
                    placeholder="john@example.com"
                    class="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:border-[#635BFF] focus:ring-1 focus:ring-[#635BFF]"
                >
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-500 mb-1">Password</label>
                <input 
                    type="password" 
                    name="password" 
                    required 
                    class="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:border-[#635BFF] focus:ring-1 focus:ring-[#635BFF]"
                >
            </div>

            <div class="flex items-center justify-between text-xs pt-1">
                <label class="flex items-center gap-2 text-slate-600">
                    <input type="checkbox" name="remember" class="w-4 h-4 rounded border-slate-300 text-black focus:ring-black">
                    Remember me
                </label>
                <a href="#" class="text-slate-600 font-medium hover:underline">Forgot Password?</a>
            </div>

            <button 
                type="submit" 
                class="w-full py-3 px-4 rounded-xl bg-[#6114ff] hover:bg-indigo-500 text-white text-xs font-bold uppercase tracking-wider transition-all shadow-md mt-2"
            >
                LOGIN
            </button>
        </form>

        <!-- Footer Link -->
        <div class="text-center text-xs text-slate-500 pt-2">
            Don't have an account? <a href="register.php" class="font-bold text-slate-800 hover:underline">Register</a>
        </div>

    </div>

</body>
</html>