<?php
// login.php
declare(strict_types=1);

session_start();

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth_stub.php';

// Agar allaqachon login bo'lgan bo'lsa – adminga yo'naltiramiz
if (!empty($_SESSION['user_id'])) {
    header('Location: admin/index.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login    = trim($_POST['login'] ?? '');
    $password = (string)($_POST['password'] ?? '');

    if ($login === '' || $password === '') {
        $error = "Login va parol majburiy.";
    } else {
        try {
            // users jadvali: id, name, login, password_hash, role_id, is_active
            $stmt = $pdo->prepare("
                SELECT 
                    u.id,
                    u.name,
                    u.login,
                    u.password_hash,
                    u.role_id,
                    u.is_active,
                    r.name AS role_name
                FROM users u
           LEFT JOIN roles r ON r.id = u.role_id
                WHERE u.login = :login
                LIMIT 1
            ");
            $stmt->execute([':login' => $login]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user || (int)$user['is_active'] !== 1) {
                $error = "Foydalanuvchi topilmadi yoki bloklangan.";
            } else {
                // Parolni tekshiramiz
                if (!password_verify($password, $user['password_hash'])) {
                    $error = "Login yoki parol noto‘g‘ri.";
                } else {
                    // Hammasi yaxshi – sessiyani tozalab, yangidan yozamiz
                    session_regenerate_id(true);

                    $_SESSION['user_id']   = (int)$user['id'];
                    $_SESSION['user_name'] = $user['name'];
                    $_SESSION['role_id']   = (int)$user['role_id'];
                    $_SESSION['role_name'] = $user['role_name'] ?? null;

                    // Eski permission cache bo‘lsa tozalaymiz
                    unset($_SESSION['user_permissions']);

                    // Dashboard / admin sahifaga yo'naltiramiz
                    header('Location: index.php');
                    exit;
                }
            }
        } catch (Throwable $e) {
            $error = "Server xatosi: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="uz">
<head>
    <meta charset="UTF-8">
    <title>Kirish – Markirovka tizimi</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body {
            background: #f3f4f6;
        }
        .login-wrapper {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-card {
            max-width: 420px;
            width: 100%;
        }
        .brand-title {
            font-weight: 700;
            font-size: 1.25rem;
        }
        .brand-sub {
            font-size: 0.9rem;
            color: #6b7280;
        }
    </style>
</head>
<body>
<div class="login-wrapper">
    <div class="card shadow-sm login-card">
        <div class="card-body p-4">
            <div class="mb-3 text-center">
                <div class="brand-title">Markirovka tizimi</div>
                <div class="brand-sub">Admin panelga kirish</div>
            </div>

            <?php if ($error !== ''): ?>
                <div class="alert alert-danger py-2">
                    <?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?>
                </div>
            <?php endif; ?>

            <form method="post" autocomplete="off">
                <div class="mb-3">
                    <label for="login" class="form-label">Login</label>
                    <input
                        type="text"
                        class="form-control"
                        id="login"
                        name="login"
                        required
                        value="<?= isset($login) ? htmlspecialchars($login, ENT_QUOTES, 'UTF-8') : ''; ?>"
                    >
                </div>

                <div class="mb-3">
                    <label for="password" class="form-label">Parol</label>
                    <input
                        type="password"
                        class="form-control"
                        id="password"
                        name="password"
                        required
                    >
                </div>

                <button type="submit" class="btn btn-primary w-100">
                    Kirish
                </button>
            </form>
        </div>
    </div>
</div>

</body>
</html>
