<?php
// login.php
include 'bd/myData.php';
require_once 'auth.php';
include 'cors.php';
setupCORS();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    $username = $data['username'] ?? '';
    $password = $data['password'] ?? '';

    if (!$username || !$password) {
        echo json_encode(array('error' => 'Username and password are required'));
        http_response_code(400);
        exit();
    }

    $query = "SELECT * FROM users WHERE username = :username";
    $params = array(':username' => $username);
    try {
        $result = metodGet($query, $params);
        $user = $result->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        echo json_encode(array('error' => 'Database error: ' . $e->getMessage()));
        http_response_code(500);
        exit();
    }

    if ($user && password_verify($password, $user['password'])) {
        // Check active status first
        if ($user['active'] != 1) {
            echo json_encode(array('error' => 'Account is deactivated'));
            http_response_code(403);
            exit();
        }
        
        unset($user['password']); // Never return the password
        
        // Generate JWT token
        $token = Auth::generateToken($user);
        
        // Return user data with token
        echo json_encode([
            'idUser' => $user['idUser'],
            'username' => $user['username'],
            'role' => $user['role'],
            'active' => $user['active'],
            'first_login' => $user['first_login'] ?? 0,
            'token' => $token
        ]);
        http_response_code(200);
    } else {
        echo json_encode(array('error' => 'Incorrect username or password!'));
        http_response_code(401);
    }
    exit();
}