<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Max-Age: 1728000');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header("HTTP/1.1 200 OK");
    exit(0);
}

include_once __DIR__ . '/config.php';

$input = file_get_contents("php://input");
$data = json_decode($input, true);

if (!isset($data['email']) || !isset($data['password'])) {
    echo json_encode([
        "success" => false,
        "error" => "Email and password are required"
    ]);
    exit;
}

$email = $data['email'];
$password = $data['password'];

// Get admin user
$stmt = $conn->prepare("SELECT * FROM adminlogin WHERE email = ? AND status = 'active'");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$admin = $result->fetch_assoc();

if (!$admin) {
    echo json_encode([
        "success" => false,
        "error" => "Invalid credentials"
    ]);
    exit;
}

// Verify password (using password_verify since we stored hashed password)
if (password_verify($password, $admin['password'])) {
    // Update last login
    $updateStmt = $conn->prepare("UPDATE adminlogin SET last_login = NOW() WHERE id = ?");
    $updateStmt->bind_param("i", $admin['id']);
    $updateStmt->execute();

    // Remove password from response
    unset($admin['password']);
    
    echo json_encode([
        "success" => true,
        "message" => "Login successful",
        "admin" => $admin
    ]);
} else {
    echo json_encode([
        "success" => false,
        "error" => "Invalid credentials"
    ]);
}