<?php
session_start();
require_once '../includes/db.php';

/* =========================
   REDIRECT IF ALREADY LOGGED IN
   ========================= */
if (isset($_SESSION['user_id'])) {
    header('Location: /pages/index.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username && $password) {

        $stmt = $pdo->prepare("
            SELECT id, username, password_hash, role, branch_id
            FROM users
            WHERE username = ?
            LIMIT 1
        ");
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password_hash'])) {

            // 🔒 Prevent session fixation
            session_regenerate_id(true);

            // ✅ Core session data
            $_SESSION['user_id']   = $user['id'];
            $_SESSION['username']  = $user['username'];
            $_SESSION['role']      = $user['role'];
            $_SESSION['branch_id'] = (int)$user['branch_id'];

            header('Location: /pages/index.php');
            exit;

        } else {
            $error = 'Invalid username or password.';
        }

    } else {
        $error = 'Please enter username and password.';
    }
}
?>

<?php include '../includes/header.php'; ?>
<link rel="stylesheet" href="/css/styles.css">

<main style="max-width: 400px; margin: 50px auto; padding: 20px; border: 1px solid #ccc; border-radius: 8px; background: #f9f9f9;">
    <h2>Login</h2>

    <?php if ($error): ?>
        <div style="color: red; margin-bottom: 15px;">
            <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <form method="POST">
        <label for="username">Username</label>
        <input
            type="text"
            name="username"
            id="username"
            required
            autofocus
            style="width: 100%; padding: 8px; margin-bottom: 10px;"
        >

        <label for="password">Password</label>
        <input
            type="password"
            name="password"
            id="password"
            required
            style="width: 100%; padding: 8px; margin-bottom: 20px;"
        >

        <button
            type="submit"
            style="padding: 10px 20px; width: 100%; background: #4E9FD1; color: white; border: none; border-radius: 5px; cursor: pointer;">
            Login
        </button>
    </form>
</main>

<?php include '../includes/footer.php'; ?>
