<?php
session_start();
define('ACCESS_ALLOWED', true);
require_once '../config/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("CSRF token tidak valid");
    }

    $username = htmlspecialchars(trim($_POST['username']), ENT_QUOTES, 'UTF-8');
    $password = trim($_POST['password']);

    if (!empty($username) && !empty($password)) {

        $checkAccountAdmin = $db->prepare("SELECT id, username, password, level, status FROM admin WHERE username = :username AND status = 1 LIMIT 1");
        $checkAccountAdmin->bindParam(':username', $username, PDO::PARAM_STR);
        $checkAccountAdmin->execute();

        if ($checkAccountAdmin->rowCount() === 1) {
            $admin = $checkAccountAdmin->fetch(PDO::FETCH_ASSOC);

            if (password_verify($password, $admin['password'])) {
                session_regenerate_id(true);
                $_SESSION['admin_id'] = $admin['id'];
                $_SESSION['level'] = $admin['level'];
                $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

                header("Location: dashboard");
                exit();
            } else {
                $_SESSION['error'] = "Invalid username or password.";
                header("Location: login");
                exit();
            }
        } else {
            $_SESSION['error'] = "Invalid username or password.";
            header("Location: login");
            exit();
        }
    } else {
        $_SESSION['error'] = "Please enter both username and password.";
        header("Location: login");
        exit();
    }
}
