<?php require_once __DIR__ . '/functions.php';
if (isLoggedIn()) { header('Location: index.php'); exit; }

$page_title = 'Login';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($email) || empty($password)) {
        flash('error', 'Please fill in all fields.');
    } else {
        $db = db();
        $stmt = $db->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if ($user && password_verify($password, $user['password'])) {
            if (!$user['is_active']) {
                flash('error', 'Your account has been deactivated.');
            } else {
                $_SESSION['user_id'] = (int)$user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user_email'] = $user['email'];
                $_SESSION['is_admin'] = (int)$user['is_admin'];
                $_SESSION['user_avatar'] = $user['avatar'];
                $_SESSION['user_state'] = $user['state'];
                
                $db->prepare("UPDATE users SET last_login_at = NOW() WHERE id = ?")->execute([$user['id']]);
                
                // Merge guest cart
                if (isset($_SESSION['cart_id'])) {
                    $guestCartId = $_SESSION['cart_id'];
                    $userCart = $db->prepare("SELECT id FROM carts WHERE user_id = ?");
                    $userCart->execute([$user['id']]);
                    $cart = $userCart->fetch();
                    
                    if ($cart) {
                        // Move items from guest cart to user cart
                        $items = $db->prepare("SELECT * FROM cart_items WHERE cart_id = ?");
                        $items->execute([$guestCartId]);
                        foreach ($items as $item) {
                            $existing = $db->prepare("SELECT * FROM cart_items WHERE cart_id = ? AND product_id = ? AND (variant_id = ? OR (variant_id IS NULL AND ? IS NULL))");
                            $existing->execute([$cart['id'], $item['product_id'], $item['variant_id'], $item['variant_id']]);
                            if ($existing->fetch()) {
                                $db->prepare("UPDATE cart_items SET quantity = quantity + ? WHERE cart_id = ? AND product_id = ? AND (variant_id = ? OR (variant_id IS NULL AND ? IS NULL))")
                                    ->execute([$item['quantity'], $cart['id'], $item['product_id'], $item['variant_id'], $item['variant_id']]);
                            } else {
                                $db->prepare("UPDATE cart_items SET cart_id = ? WHERE id = ?")->execute([$cart['id'], $item['id']]);
                            }
                        }
                        $db->prepare("DELETE FROM carts WHERE id = ?")->execute([$guestCartId]);
                        $_SESSION['cart_id'] = $cart['id'];
                    } else {
                        $db->prepare("UPDATE carts SET user_id = ? WHERE id = ?")->execute([$user['id'], $guestCartId]);
                    }
                }
                
                flash('success', 'Welcome back, ' . $user['name'] . '!');
                $redirect = $_GET['redirect'] ?? ($user['is_admin'] ? 'admin/dashboard.php' : 'account/dashboard.php');
                header('Location: ' . $redirect);
                exit;
            }
        } else {
            flash('error', 'Invalid email or password.');
        }
    }
}

require_once __DIR__ . '/includes/header.php';
?>
<div class="min-h-[70vh] flex items-center justify-center px-4">
    <div class="w-full max-w-md bg-white rounded-xl shadow-sm border border-gray-200 p-8">
        <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">Login to <?= APP_NAME ?></h2>
        <form method="POST">
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input type="email" name="email" value="<?= h($_POST['email'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                <input type="password" name="password" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
            </div>
            <button type="submit" class="w-full bg-primary-600 text-white py-2.5 rounded-lg font-semibold hover:bg-primary-700 transition">Login</button>
        </form>
        <p class="text-center text-sm text-gray-500 mt-4">Don't have an account? <a href="register.php" class="text-primary-600 hover:underline">Register</a></p>
    </div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
