<?php
// login_process.php - Handles admin login form submission

// Start a PHP session
// This must be the very first thing in your PHP script, before any output.
session_start();

// Include the database configuration file
// IMPORTANT: Ensure 'config.php' is in the same directory as this file.
require_once 'config.php';

// Set header to return JSON response
// This tells the browser that the response will be a JSON object
header('Content-Type: application/json');

// Check if the request method is POST
// This script should only be accessed via a POST request from the login form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the raw POST data from the request body
    // This is how PHP reads JSON data sent from a JavaScript fetch API call
    $input = file_get_contents('php://input');
    $data = json_decode($input, true); // Decode the JSON string into an associative PHP array

    // Validate and sanitize input data
    // FILTER_SANITIZE_STRING removes HTML tags and special characters.
    $username = filter_var($data['username'] ?? '', FILTER_SANITIZE_STRING);
    $password = $data['password'] ?? ''; // Password will be verified, not sanitized as a string

    // Basic server-side validation
    // Check if username or password fields are empty
    if (empty($username) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Username and password are required.']);
        exit; // Stop script execution
    }

    // Prepare a SELECT statement to retrieve admin by username
    // Using prepared statements with PDO is CRITICAL for preventing SQL injection attacks.
    // We fetch the password_hash to verify it against the provided password.
    $sql = "SELECT admin_id, username, password_hash, full_name, is_super_admin FROM admins WHERE username = :username";

    try {
        // Prepare the statement using the PDO connection object ($pdo from config.php)
        $stmt = $pdo->prepare($sql);

        // Bind parameters
        // This links the PHP variable to the SQL placeholder securely.
        $stmt->bindParam(':username', $username);

        // Execute the prepared statement
        $stmt->execute();

        // Fetch the admin record
        // fetch() retrieves the next row from a result set as an associative array.
        $admin = $stmt->fetch();

        // Check if an admin with the given username exists AND verify the password
        // password_verify() securely checks a plain-text password against a hashed password.
        if ($admin && password_verify($password, $admin['password_hash'])) {
            // Password is correct, start a new session or regenerate current one for security
            session_regenerate_id(true); // Regenerate session ID to prevent session fixation attacks

            // Store necessary admin data in session variables
            // This data will be available across different PHP pages as long as the session is active.
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_id'] = $admin['admin_id'];
            $_SESSION['is_super_admin'] = $admin['is_super_admin'];
            $_SESSION['username'] = $admin['username'];
            $_SESSION['full_name'] = $admin['full_name'];

            // Send a success JSON response, including a redirect URL to the dashboard
            echo json_encode(['success' => true, 'message' => 'Login successful!', 'redirect' => 'admin_dashboard.php']);
        } else {
            // If admin does not exist or password does not match, send a failure message
            echo json_encode(['success' => false, 'message' => 'Invalid username or password.']);
        }
    } catch (PDOException $e) {
        // Catch any PDO (database) exceptions and return a database error message
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    // If the request method is not POST (e.g., someone tries to access it directly via GET)
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>
