<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/referrals.php';
header('Content-Type: application/json');

start_session();
$u = $_SESSION['user'] ?? null;
if (!$u) { http_response_code(401); echo json_encode(['error'=>'unauthorized']); exit; }
$uid = (int)$u['id'];

$code = ensure_user_ref_code($pdo, $uid);
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
$link = $baseUrl . "/register.php?ref=" . $code;
$counts = $pdo->prepare("
  SELECT
    (SELECT COUNT(*) FROM referral_registrations WHERE referrer_id=?) as registrations,
    (SELECT COUNT(*) FROM commissions WHERE referrer_id=? AND status IN ('pending','approved','paid','processed')) as commissions_count,
    (SELECT COALESCE(SUM(amount),0) FROM commissions WHERE referrer_id=? AND status IN ('pending','approved','paid','processed')) as commissions_total,
    (SELECT COALESCE(SUM(amount),0) FROM commissions WHERE referrer_id=? AND status IN ('paid','processed')) as commissions_paid
");
$counts->execute([$uid,$uid,$uid,$uid]);
$data = $counts->fetch() ?: ['registrations'=>0,'commissions_count'=>0,'commissions_total'=>0,'commissions_paid'=>0];
echo json_encode([
  'code'=>$code,
  'link'=>$link,
  'stats'=>[
    'registrations'=>(int)$data['registrations'],
    'commissions_count'=>(int)$data['commissions_count'],
    'commissions_total'=>(float)$data['commissions_total'],
    'commissions_paid'=>(float)$data['commissions_paid'],
  ]
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
