<?php
/**
 * Admin Authentication API
 * Handles admin login and session management.
 */

require_once '../includes/config.php';
session_start();

header('Content-Type: application/json');

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

    if (empty($email) || empty($password)) {
        echo json_encode(['status' => 'error', 'message' => 'Email and Password are required.']);
        exit;
    }

    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND role = 'admin'");
        $stmt->execute([$email]);
        $admin = $stmt->fetch();

        if ($admin && password_verify($password, $admin['password'])) {
            $_SESSION['admin_id']        = $admin['id'];
            $_SESSION['admin_name']      = $admin['full_name'];
            $_SESSION['admin_email']     = $admin['email'];
            $_SESSION['admin_logged_in'] = true;

            echo json_encode([
                'status'  => 'success',
                'message' => 'Welcome back, ' . $admin['full_name'] . '!',
                'admin'   => [
                    'id'        => $admin['id'],
                    'full_name' => $admin['full_name'],
                    'email'     => $admin['email'],
                ]
            ]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invalid admin credentials.']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
