<?php
// Set headers for JSON response
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

// Import the JWT class
use Firebase\JWT\JWT;

// Bootstrap the application
require_once '../../../core/bootstrap.php';

// Instantiate User model
$user = new User();

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['message' => 'Method Not Allowed']);
    exit();
}

// Get raw posted data
$data = json_decode(file_get_contents("php://input"));

// Basic validation
if (empty($data->email) || empty($data->password)) {
    http_response_code(400); // Bad Request
    echo json_encode(['message' => 'Email and password are required.']);
    exit();
}

// Attempt to log the user in
$loggedInUser = $user->login($data->email, $data->password);

if ($loggedInUser) {
    // Login successful, generate JWT
    $issuedAt = time();
    $expirationTime = $issuedAt + (60 * 60 * 24); // jwt valid for 24 hours
    $payload = [
        'iat' => $issuedAt,
        'exp' => $expirationTime,
        'iss' => JWT_ISSUER,
        'aud' => JWT_AUDIENCE,
        'sub' => $loggedInUser->id, // Standard subject claim for user ID
        'data' => [
            'id' => $loggedInUser->id,
            'username' => $loggedInUser->username,
            'email' => $loggedInUser->email,
            'role' => $loggedInUser->role
        ]
    ];

    $jwt = JWT::encode($payload, JWT_KEY, 'HS256');

    http_response_code(200); // OK
    echo json_encode([
        'message' => 'Login successful.',
        'token' => $jwt
    ]);
} else {
    // Login failed
    http_response_code(401); // Unauthorized
    echo json_encode(['message' => 'Login failed. Invalid credentials.']);
}
?>