<?php
// File: /admin/login_handler.php
session_start();
require_once __DIR__ . '/../db.php'; // Correctly locate db.php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (empty($username) || empty($password)) {
        header("Location: login.php?error=empty");
        exit();
    }

    // Prepare a statement to prevent SQL injection
    $stmt = $conn->prepare("SELECT id, username, password_hash, role FROM users WHERE username = ? OR email = ?");
    $stmt->bind_param("ss", $username, $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        // Verify the password and check if the user is an admin
        if (password_verify($password, $user['password_hash'])) {
            if ($user['role'] === 'admin') {
                // Password is correct and user is an admin, start a session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];

                // Redirect to the admin dashboard
                header("Location: index.php");
                exit();
            } else {
                // Correct credentials, but not an admin
                header("Location: login.php?error=not_admin");
                exit();
            }
        } else {
            // Incorrect password
            header("Location: login.php?error=invalid");
            exit();
        }
    } else {
        // No user found with that username/email
        header("Location: login.php?error=invalid");
        exit();
    }

    $stmt->close();
    $conn->close();
} else {
    // Redirect if accessed directly
    header("Location: login.php");
    exit();
}
?>
