<?php

require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once '../../helpers/request.php';

// Load JWT library
require_once '../../vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if ($method !== 'POST') {
    sendError('Method not allowed', 405);
}

$data = getRequestData();
validateRequiredFields($data, ['email', 'password']);

try {
    // Get user by email
    $stmt = $pdo->prepare("
        SELECT id, name, email, password, role_id, status 
        FROM users 
        WHERE email = :email
    ");
    $stmt->execute([':email' => $data['email']]);
    $user = $stmt->fetch();
    
    // Check if user exists
    if (!$user) {
        sendError('Invalid credentials', 401);
    }
    
    // Check if account is blocked
    if ($user['status'] === 'blocked') {
        sendError('Account is blocked. Contact administrator.', 403);
    }
    
    // Verify password
    if (!password_verify($data['password'], $user['password'])) {
        sendError('Invalid credentials', 401);
    }
    
    // Get role name
    $roleStmt = $pdo->prepare("SELECT name FROM roles WHERE id = :id");
    $roleStmt->execute([':id' => $user['role_id']]);
    $role = $roleStmt->fetchColumn();
    
    // Generate JWT token
    $secret_key = "gqMMHpK0t49m429j4C.dQ/gO/2uXsHPHazBwIudnd.xD3O1Vi."; // Change this!
    $issued_at = time();
    $expiration_time = $issued_at + (60 * 60 * 24); // 24 hours
    
    $payload = [
        'user_id' => $user['id'],
        'email' => $user['email'],
        'role_id' => $user['role_id'],
        'role' => $role,
        'iat' => $issued_at,
        'exp' => $expiration_time
    ];
    
    $jwt = JWT::encode($payload, $secret_key, 'HS256');
    
    sendSuccess([
        'id' => $user['id'],
        'name' => $user['name'],
        'email' => $user['email'],
        'role' => $role,
        'token' => $jwt,
        'expires_at' => $expiration_time
    ], 'Login successful');
    
} catch (PDOException $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    sendError('Authentication error: ' . $e->getMessage(), 500);
}
?>