<?php
require_once __DIR__ . '/bootstrap.php';
// endpoints/admin_auth.php

$db = Database::getInstance();

// POST /admin/auth/login
if ($method === 'POST' && strpos($uri, '/admin/auth/login') !== false) {
    $email    = filter_var($input['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $password = $input['password'] ?? '';

    if (!$email || !$password) jsonError('Email and password are required.');

    $admin = $db->fetch("SELECT * FROM admins WHERE email=? AND status=1 LIMIT 1", [$email]);
    if (!$admin || !($password == $admin['password'])) jsonError('Invalid credentials.', 401);

    $db->query("UPDATE admins SET last_login=NOW() WHERE id=?", [$admin['id']]);

    $jwt = createJWT([
        'admin_id' => $admin['id'],
        'email'    => $admin['email'],
        'role'     => $admin['role'],
    ]);

    jsonSuccess([
        'token' => $jwt,
        'admin' => ['id'=>$admin['id'],'name'=>$admin['name'],'email'=>$admin['email'],'role'=>$admin['role']]
    ], 'Login successful');
}
