<?php
require 'config.php'; // loads autoload, constants, dbclass
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

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

// Get POST or GET data
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
} else {
    $data = $_GET;
}

// Validate input
if (empty($data['email']) || empty($data['password'])) {
    http_response_code(400);
    exit(json_encode(["error" => "Email and password required"]));
}

$username = $data['email'];
$password = encrypt($data['password']); // your encrypt function

// Find user
$user = findQuery("SELECT * FROM tbl_user WHERE username = '$username' AND password = '$password' ORDER BY id DESC");

if (!$user) {
    http_response_code(401);
    exit(json_encode(["error" => "Invalid credentials"]));
}

// Access Token payload
$payload = [
    "iss" => JWT_ISSUER,
    "iat" => time(),
    "nbf" => time(), // token valid immediately; you can delay if needed
    "exp" => time() + JWT_EXPIRE,
    "user_id" => $user[0]['id'],
    "email" => $user[0]['username'],
    "role" => (isset($user[0]['user_type']) && $user[0]['user_type'] == 1) ? 'admin' : 'user'
];

// Generate Access Token
$access_token = JWT::encode($payload, JWT_SECRET, JWT_ALGO);

// Generate Refresh Token
$refresh_token = bin2hex(random_bytes(32));
$hashed_token = password_hash($refresh_token, PASSWORD_DEFAULT);

// Save hashed refresh token in DB
$data = [
    "user_id" => $user[0]['id'],
    "token" => $hashed_token,
    "expires_at" => time() + REFRESH_EXPIRE
];
$id = saveArray('tbl_refresh_tokens', $data, 0);

// Return tokens and user info
echo json_encode([
    "access_token" => $access_token,
    "expires_in" => JWT_EXPIRE,
    "refresh_token" => $refresh_token,
    "user" => [
        "id" => $user[0]['id'],
        "email" => $user[0]['username'],
        "role" => (isset($user[0]['user_type']) && $user[0]['user_type'] == 1) ? 'admin' : 'user'
    ]
]);
