<?php
session_start();
// Use relative paths to access files outside the 'admin' directory
require_once '../config/database.php';

// Set the header to JSON *before* any potential output
header('Content-Type: application/json');

// This function will handle sending all JSON responses and exiting the script
function send_json_response($data) {
    echo json_encode($data);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();

    // Get the raw POST data and decode it
    $inputJSON = file_get_contents('php://input');
    $input = json_decode($inputJSON, true);

    // Check if JSON decoding was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid request format.');
    }

    // Validate CSRF token using hash_equals for timing-attack resistance
    if (empty($input['csrf_token']) || empty($_SESSION['admin_csrf_token']) || !hash_equals($_SESSION['admin_csrf_token'], $input['csrf_token'])) {
        throw new Exception('Invalid security token. Please refresh and try again.');
    }
    
    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';

    if (empty($username) || empty($password)) {
        throw new Exception("Username and password are required.");
    }

    // Query for an admin user from the separate admin_users table
    $stmt = $db->prepare("SELECT * FROM admin_users WHERE username = :username");
    $stmt->execute([':username' => $username]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    // Verify user and password
    if (!$admin || !password_verify($password, $admin['password'])) {
        throw new Exception("Invalid credentials provided.");
    }

    // Check account status
    if ($admin['status'] !== 'active') {
        throw new Exception('Your admin account is inactive. Please contact the system administrator.');
    }

    // Login successful: Invalidate the old CSRF token
    unset($_SESSION['admin_csrf_token']);
    
    // Regenerate session ID to prevent session fixation attacks
    session_regenerate_id(true); 
    
    // Set admin-specific session variables
    $_SESSION['admin_id'] = $admin['id'];
    $_SESSION['admin_name'] = $admin['first_name'];
    $_SESSION['admin_logged_in'] = true;

    send_json_response([
        'success' => true,
        'message' => 'Login successful!',
        'redirect' => 'dashboard.php'
    ]);

} catch (Exception $e) {
    // Regenerate a new token on failure and send it back to the client
    $_SESSION['admin_csrf_token'] = bin2hex(random_bytes(32));
    
    // Log the detailed error for your records
    error_log("Admin Login Error: " . $e->getMessage());
    
    // Send a user-friendly error message
    http_response_code(401); // Unauthorized
    send_json_response([
        'success' => false,
        'message' => $e->getMessage(),
        'new_csrf_token' => $_SESSION['admin_csrf_token'] // Send the new token for the next try
    ]);
}
?>
