<?php
// =====================================================
// POST /login-admin.php
// Params: email, password
// Response: { status, message, admin: { id, name, mail, role } }
// =====================================================
require_once 'config.php';

$conn = getConnection();

$email    = $_POST['email']    ?? '';
$password = $_POST['password'] ?? '';

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

$stmt = $conn->prepare("SELECT id, name, mail, password, role FROM admins WHERE mail = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(["status" => "error", "message" => "Invalid email or password"]);
    exit;
}

$admin = $result->fetch_assoc();

if (!password_verify($password, $admin['password'])) {
    echo json_encode(["status" => "error", "message" => "Invalid email or password"]);
    exit;
}

echo json_encode([
    "status"  => "success",
    "message" => "Login successful",
    "admin"   => [
        "id"   => (int)$admin['id'],
        "name" => $admin['name'],
        "mail" => $admin['mail'],
        "role" => $admin['role']
    ]
]);

$stmt->close();
$conn->close();