<?php
/**
 * Authentication Endpoints
 */

$db = Database::getInstance()->getConnection();

// Login endpoint
if ($method === 'POST' && $id === 'login') {
    $input = getJsonInput();
    
    // Validate input
    $errors = validateRequired($input, ['email', 'password']);
    if (!empty($errors)) {
        jsonResponse(['error' => implode(', ', $errors)], 400);
    }
    
    $email = sanitizeString($input['email']);
    $password = $input['password'];
    
    // Find admin user
    $stmt = $db->prepare("SELECT * FROM admin_users WHERE email = ?");
    $stmt->execute([$email]);
    $admin = $stmt->fetch();
    
    if (!$admin) {
        jsonResponse(['error' => 'Invalid email or password'], 401);
    }
    
    // Verify password
    if (!password_verify($password, $admin['password_hash'])) {
        jsonResponse(['error' => 'Invalid email or password'], 401);
    }
    
    // Create token
    $token = JWT::createToken($email);
    
    jsonResponse([
        'access_token' => $token,
        'token_type' => 'bearer',
        'email' => $email
    ]);
}

// Verify token endpoint
if ($method === 'POST' && $id === 'verify') {
    $payload = requireAuth();
    
    jsonResponse([
        'valid' => true,
        'email' => $payload['sub']
    ]);
}

jsonResponse(['error' => 'Invalid auth endpoint'], 404);
