<?php
// panel_data.php
// API پنل برای اطلاعات کاربر، سرویس‌ها، پرداخت‌ها، کانفیگ‌ها و موجودی کیف پول

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

if (empty($_SESSION['user_email'])) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'not_logged_in', 'message' => 'ابتدا وارد شوید.']);
    exit;
}

require __DIR__ . '/db.php';

/* ===== Helper ها ===== */

function fa_digits(string $str): string {
    $en = ['0','1','2','3','4','5','6','7','8','۹'];
    $fa = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
    return str_replace($en, $fa, $str);
}

function gregorian_to_jalali(int $gy, int $gm, int $gd): array {
    $g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
    $gy2 = ($gm > 2) ? ($gy + 1) : $gy;
    $days = 355666 + (365 * $gy)
        + intdiv($gy2 + 3, 4)
        - intdiv($gy2 + 99, 100)
        + intdiv($gy2 + 399, 400)
        + $gd + $g_d_m[$gm-1];
    $jy = -1595 + 33 * intdiv($days, 12053);
    $days %= 12053;
    $jy += 4 * intdiv($days, 1461);
    $days %= 1461;
    if ($days > 365) {
        $jy += intdiv($days - 1, 365);
        $days = ($days - 1) % 365;
    }
    $jm = ($days < 186) ? 1 + intdiv($days, 31) : 7 + intdiv($days - 186, 30);
    $jd = 1 + (($days < 186) ? ($days % 31) : (($days - 186) % 30));
    return [$jy, $jm, $jd];
}

function format_shamsi_datetime($ts): string {
    if (!is_int($ts)) {
        $ts = strtotime((string)$ts);
        if ($ts === false) return '—';
    }

    $gy = (int)date('Y', $ts);
    $gm = (int)date('m', $ts);
    $gd = (int)date('d', $ts);
    $H  = date('H', $ts);
    $i  = date('i', $ts);

    [$jy, $jm, $jd] = gregorian_to_jalali($gy,$gm,$gd);

    $jm2 = ($jm < 10 ? '0'.$jm : (string)$jm);
    $jd2 = ($jd < 10 ? '0'.$jd : (string)$jd);

    $out = $jy.'/'.$jm2.'/'.$jd2.' - '.$H.':'.$i;
    return fa_digits($out);
}

function fa_money($rial): string {
    $num = (int)$rial;
    $formatted = number_format($num);
    return fa_digits($formatted);
}

/* ===== Query ===== */

$email = $_SESSION['user_email'];

try {

    // کاربر + موجودی کیف پول
    $stmt = $pdo->prepare("
      SELECT 
        id,
        email,
        site_username,
        site_password,
        telegram_id,
        telegram_username,
        telegram_first_name,
        telegram_last_name,
        wallet_balance
      FROM users
      WHERE email = :e
      LIMIT 1
    ");
    $stmt->execute([':e' => $email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

    if (!$user) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'user_not_found', 'message' => 'کاربر یافت نشد.']);
        exit;
    }

    // سرویس‌ها (شامل configs + panel_key از جدول vpn_panels با JOIN)
    $stmt2 = $pdo->prepare("
        SELECT 
            s.*,
            vp.panel_key AS vpn_panel_key
        FROM services s
        LEFT JOIN vpn_panels vp ON vp.id = s.panel_id
        WHERE s.user_id = :uid
        ORDER BY s.id DESC
    ");
    $stmt2->execute([':uid' => (int)$user['id']]);
    $services = $stmt2->fetchAll(PDO::FETCH_ASSOC) ?: [];

    // پرداخت‌ها
    $stmt3 = $pdo->prepare("
        SELECT id, created_at, plan, amount_rial, ref_id, status
        FROM payments
        WHERE email = :e
        ORDER BY id DESC
        LIMIT 200
    ");
    $stmt3->execute([':e' => $email]);
    $payments = $stmt3->fetchAll(PDO::FETCH_ASSOC) ?: [];

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => 'خطا در خواندن اطلاعات.']);
    exit;
}

/* ===== محاسبات سرویس ===== */

$active_count    = 0;
$expired_count   = 0;
$total_all_bytes = 0;
$used_all_bytes  = 0;
$nearestDays     = null;
$now             = time();

$services_out = [];

foreach ($services as $svc) {
    $st = strtolower($svc['status'] ?? '');

    if (in_array($st, ['active', 'on_hold'], true)) {
        $active_count++;
    } else {
        $expired_count++;
    }

    $totalBytes = isset($svc['data_limit_bytes'])
        ? (float)$svc['data_limit_bytes']
        : (float)(($svc['plan_size_gb'] ?? 0) * 1024 * 1024 * 1024);

    $usedBytes = isset($svc['used_bytes'])
        ? (float)$svc['used_bytes']
        : (float)(($svc['up_bytes'] ?? 0) + ($svc['down_bytes'] ?? 0));

    $remBytes  = max(0.0, $totalBytes - $usedBytes);

    $total_all_bytes += $totalBytes;
    $used_all_bytes  += $usedBytes;

    $usedGB  = $usedBytes > 0 ? round($usedBytes / (1024*1024*1024), 2) : 0;
    $totalGB = $totalBytes > 0 ? round($totalBytes / (1024*1024*1024), 0) : (int)($svc['plan_size_gb'] ?? 0);
    $remGB   = $totalBytes > 0 ? max(0, round($remBytes / (1024*1024*1024), 2)) : 0;
    $pct     = ($totalBytes > 0) ? min(100, round(($usedBytes / $totalBytes) * 100)) : 0;

    $expireUnix = !empty($svc['expire_unix'])
        ? (int)$svc['expire_unix']
        : (!empty($svc['expire_at']) ? strtotime($svc['expire_at']) : 0);

    $daysLeft = null;
    if ($expireUnix) {
        $diff     = $expireUnix - $now;
        $daysLeft = max(0, (int)ceil($diff / 86400));
        if ($nearestDays === null || $daysLeft < $nearestDays) {
            $nearestDays = $daysLeft;
        }
    }

    // کانفیگ‌ها از ستون configs
    $configsRaw = $svc['configs'] ?? null;
    $configsArr = [];
    if ($configsRaw) {
        $tmp = json_decode($configsRaw, true);
        if (is_array($tmp)) {
            $configsArr = $tmp;
        }
    }

    // panel_key از JOIN با vpn_panels
    $panelKey = $svc['vpn_panel_key'] ?? '';

    $services_out[] = [
        'id'               => (int)$svc['id'],
        'marzban_user'     => $svc['marzban_user'] ?? '',
        'subscription_url' => $svc['subscription_url'] ?? '',
        'status'           => $svc['status'] ?? '',
        'status_label'     => [
            'active'   => 'فعال',
            'expired'  => 'منقضی',
            'disabled' => 'غیرفعال',
            'on_hold'  => 'معلق'
        ][$st] ?? ($svc['status'] ?? ''),
        'used_gb'          => $usedGB,
        'total_gb'         => $totalGB,
        'remain_gb'        => $remGB,
        'percent'          => $pct,
        'expire_unix'      => $expireUnix,
        'days_left'        => $daysLeft,
        'configs'          => $configsArr,
        'panel_key'        => $panelKey,
    ];
}

/* overall usage */
if ($total_all_bytes > 0) {
    $usedGB_all  = round($used_all_bytes / (1024*1024*1024), 2);
    $totalGB_all = round($total_all_bytes / (1024*1024*1024), 0);
    $pct_all     = min(100, round(($used_all_bytes / $total_all_bytes) * 100));
} else {
    $usedGB_all  = $used_all_bytes > 0 ? round($used_all_bytes / (1024*1024*1024), 2) : 0;
    $totalGB_all = null;
    $pct_all     = 0;
}

/* ===== پرداخت‌ها ===== */

$payments_out = [];
foreach ($payments as $p) {
    $planTitle = is_array($p['plan'] ?? null)
        ? ($p['plan']['title'] ?? '')
        : ($p['plan'] ?? '');

    $createdRaw = $p['created_at'] ?? '';
    $createdTs  = strtotime($createdRaw) ?: null;

    $payments_out[] = [
        'id'              => (int)$p['id'],
        'created_at'      => $createdRaw,
        'created_at_fa'   => $createdTs ? format_shamsi_datetime($createdTs) : '—',
        'plan_title'      => $planTitle,
        'amount_rial'     => (int)($p['amount_rial'] ?? 0),
        'amount_rial_fa'  => fa_money($p['amount_rial'] ?? 0),
        'ref_id'          => $p['ref_id'] ?? '',
        'status'          => $p['status'] ?? '',
    ];
}

/* ===== خروجی نهایی ===== */

$wallet_raw = (int)($user['wallet_balance'] ?? 0);

echo json_encode([
    'ok'    => true,
    'user'  => [
        'email'             => $user['email'],
        'site_username'     => $user['site_username'] ?? '',
        'wallet_balance'    => $wallet_raw,
        'wallet_balance_fa' => fa_money($wallet_raw),
        'telegram'          => [
            'id'         => $user['telegram_id'] ?? null,
            'username'   => $user['telegram_username'] ?? '',
            'first_name' => $user['telegram_first_name'] ?? '',
            'last_name'  => $user['telegram_last_name'] ?? '',
        ]
    ],
    'stats' => [
        'services_total'      => count($services),
        'services_active'     => $active_count,
        'services_expired'    => $expired_count,
        'overall_used_gb'     => $usedGB_all,
        'overall_total_gb'    => $totalGB_all,
        'overall_percent'     => $pct_all,
        'nearest_expire_days' => $nearestDays,
    ],
    'services' => $services_out,
    'payments' => $payments_out,
], JSON_UNESCAPED_UNICODE);
