<?php
require_once '../config/headers.php';
require_once '../config/database.php';
require_once '../utils/response.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, 'error', 'Method not allowed');
}

// Get raw JSON data from React fetch request
$data = json_decode(file_get_contents("php://input"));

if (empty($data->email) || empty($data->password)) {
    sendResponse(400, 'error', 'Email and password are required');
}

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

try {
    // 1. Find the admin by email
    $query = "SELECT id, first_name, last_name, password_hash, role, status FROM admins WHERE email = :email LIMIT 1";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':email', $data->email);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        $admin = $stmt->fetch();

        // 2. Check if account is active
        if ($admin['status'] !== 'active') {
            sendResponse(403, 'error', 'Account is suspended or inactive');
        }

        // 3. Verify the password
        if (password_verify($data->password, $admin['password_hash'])) {
            
            // 4. Update last_login timestamp
            $updateQuery = "UPDATE admins SET last_login = NOW() WHERE id = :id";
            $updateStmt = $db->prepare($updateQuery);
            $updateStmt->bindParam(':id', $admin['id']);
            $updateStmt->execute();

            // 5. Return success data (do NOT return the password hash)
            sendResponse(200, 'success', 'Login successful', [
                'id' => $admin['id'],
                'name' => $admin['first_name'] . ' ' . $admin['last_name'],
                'role' => $admin['role']
            ]);
        } else {
            sendResponse(401, 'error', 'Invalid admin email or password');
        }
    } else {
        sendResponse(401, 'error', 'Invalid admin email or password');
    }
} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>