<?php
require_once '../config.php';
require_once '../middleware.php';

### API Blueprint: /admin/login
# POST /admin/login
# Description: Authenticates an admin and returns a token.
# Request Body:
#   - username: string (required)
#   - password: string (required)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Login successful",
#       "data": {
#         "token": "admin_token_example"
#       }
#     }
#   - 400: Invalid input
#   - 401: Invalid credentials
#   - 500: Database connection failed

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the encrypted payload
    $encrypted_payload = file_get_contents('php://input');
    if (empty($encrypted_payload)) {
        sendResponse(400, 'Empty request body');
    }

    // Decrypt the payload
    $data = decryptRequestPayload($encrypted_payload);
    if (!$data) {
        sendResponse(400, 'Invalid request body');
    }

    validateInput($data, ['username', 'password']);
    $username = $data['username'];
    $password = $data['password'];

    $valid_username = 'admin';
    $valid_password = 'admin123'; // In production, use hashed passwords and proper auth

    if ($username !== $valid_username || $password !== $valid_password) {
        sendResponse(401, 'Invalid credentials');
    }

    $token = 'admin_token_example'; // In production, generate a proper JWT or token
    sendResponse(200, 'Login successful', ['token' => $token]);
}
?>