<?php
require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json; charset=UTF-8');

// INPUT (support multiple param names)
$username = $_GET['username'] ?? $_GET['user'] ?? null;
$password = $_GET['password'] ?? $_GET['pass'] ?? null;

if (!$username || !$password) {
    deny("Invalid credentials");
}

// FETCH USER (panel-only)
$ret = $db->select(
    'menualuser',
    '*',
    'username = :username AND role = \'client\'',
    '',
    [':username' => $username]
);

if (!$ret || !isset($ret[0])) {
    deny("Invalid login");
}

$user = $ret[0];

// PASSWORD CHECK (RAW)
if ((string)$user['password'] !== (string)$password) {
    deny("Invalid login");
}

// EXPIRY CHECK
if (empty($user['expire_date']) || strtotime($user['expire_date']) < time()) {
    deny("Account expired");
}

// SUCCESS (XC-style response)
$now = time();
$exp = (string)(strtotime($user['expire_date']) + 86399);

echo json_encode([
    "user_info" => [
        "username" => $user['username'],
        "password" => $user['password'],
        "auth" => 1,
        "status" => "Active",
        "exp_date" => $exp,
        "is_trial" => "0",
        "active_cons" => "0",
        "created_at" => (string)$now,
        "max_connections" => "1",
        "allowed_output_formats" => ["m3u8", "ts"]
    ],
    "server_info" => [
        "url" => $_SERVER['HTTP_HOST'],
        "port" => "80",
        "https_port" => "443",
        "server_protocol" => "http",
        "timezone" => "UTC",
        "timestamp_now" => $now,
        "time_now" => date("Y-m-d H:i:s", $now)
    ]
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;

// --------
function deny($msg) {
    echo json_encode([
        "user_info" => [
            "auth" => 0,
            "status" => $msg
        ]
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}