<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';

mocker_admin_require_permission('dashboard');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

require_once __DIR__ . '/db.php';

$now = time();
$from = isset($_GET['from']) ? (int) $_GET['from'] : 0;
$to = isset($_GET['to']) ? (int) $_GET['to'] : 0;

if ($from <= 0 || $to <= 0) {
    $from = $now - ($now % 86400);
    $to = $now;
}
if ($from > $to) {
    $tmp = $from;
    $from = $to;
    $to = $tmp;
}

$maxSpan = 366 * 86400;
if ($to - $from > $maxSpan) {
    $from = $to - $maxSpan;
}

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$st = $pdo->query('SELECT COUNT(*) AS c FROM users');
$totalUsers = (int) $st->fetchColumn();

$st = $pdo->prepare(
    'SELECT COUNT(*) FROM users WHERE created_at >= :f AND created_at <= :t'
);
$st->execute([':f' => $from, ':t' => $to]);
$newUsersInRange = (int) $st->fetchColumn();

$st = $pdo->prepare(
    'SELECT COUNT(*) FROM users WHERE last_login_at IS NOT NULL AND last_login_at >= :f AND last_login_at <= :t'
);
$st->execute([':f' => $from, ':t' => $to]);
$loginsInRange = (int) $st->fetchColumn();

$st = $pdo->prepare(
    'SELECT COUNT(*) FROM users WHERE last_seen_at IS NOT NULL AND last_seen_at >= :f AND last_seen_at <= :t'
);
$st->execute([':f' => $from, ':t' => $to]);
$activeInRange = (int) $st->fetchColumn();

$t24 = $now - 86400;
$st = $pdo->prepare(
    'SELECT COUNT(*) FROM users WHERE last_seen_at IS NOT NULL AND last_seen_at >= :t'
);
$st->execute([':t' => $t24]);
$activeLast24h = (int) $st->fetchColumn();

$st = $pdo->prepare(
    'SELECT COUNT(*), COALESCE(SUM(price), 0) FROM purchases WHERE created_at >= :f AND created_at <= :t'
);
$st->execute([':f' => $from, ':t' => $to]);
$row = $st->fetch(PDO::FETCH_NUM);
$purchasesCount = (int) ($row[0] ?? 0);
$purchasesCoinsSum = (int) ($row[1] ?? 0);

$st = $pdo->query('SELECT COALESCE(SUM(coins), 0) FROM users');
$totalCoinsSum = (int) $st->fetchColumn();

$usersActiveAccount = $totalUsers;
$usersInactiveAccount = 0;
try {
    $st = $pdo->query('SELECT COUNT(*) FROM users WHERE COALESCE(is_active, 1) = 1');
    $usersActiveAccount = (int) $st->fetchColumn();
    $st = $pdo->query('SELECT COUNT(*) FROM users WHERE COALESCE(is_active, 1) = 0');
    $usersInactiveAccount = (int) $st->fetchColumn();
} catch (Throwable $e) {
    
}

$usersNeverLoggedIn = 0;
try {
    $st = $pdo->query('SELECT COUNT(*) FROM users WHERE last_login_at IS NULL');
    $usersNeverLoggedIn = (int) $st->fetchColumn();
} catch (Throwable $e) {
    
}

$purchasesByStatus = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
try {
    $st = $pdo->prepare(
        'SELECT COALESCE(LOWER(TRIM(status)), \'pending\') AS s, COUNT(*) AS c FROM purchases WHERE created_at >= :f AND created_at <= :t GROUP BY COALESCE(LOWER(TRIM(status)), \'pending\')'
    );
    $st->execute([':f' => $from, ':t' => $to]);
    while ($r = $st->fetch(PDO::FETCH_ASSOC)) {
        $k = (string) ($r['s'] ?? 'pending');
        if (!in_array($k, ['pending', 'approved', 'rejected'], true)) {
            $k = 'pending';
        }
        $purchasesByStatus[$k] += (int) ($r['c'] ?? 0);
    }
} catch (Throwable $e) {
    
}

$complaintsByStatus = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
$complaintsInRange = 0;
try {
    $st = $pdo->prepare(
        'SELECT COALESCE(LOWER(TRIM(status)), \'pending\') AS s, COUNT(*) AS c FROM complaints WHERE created_at >= :f AND created_at <= :t GROUP BY COALESCE(LOWER(TRIM(status)), \'pending\')'
    );
    $st->execute([':f' => $from, ':t' => $to]);
    while ($r = $st->fetch(PDO::FETCH_ASSOC)) {
        $k = (string) ($r['s'] ?? 'pending');
        if (!in_array($k, ['pending', 'approved', 'rejected'], true)) {
            $k = 'pending';
        }
        $c = (int) ($r['c'] ?? 0);
        $complaintsByStatus[$k] += $c;
        $complaintsInRange += $c;
    }
} catch (Throwable $e) {
    
}

$wheelSpinsCount = 0;
$wheelCoinsAwarded = 0;
try {
    $st = $pdo->prepare(
        'SELECT COUNT(*), COALESCE(SUM(amount), 0) FROM wheel_spins WHERE created_at >= :f AND created_at <= :t'
    );
    $st->execute([':f' => $from, ':t' => $to]);
    $wr = $st->fetch(PDO::FETCH_NUM);
    $wheelSpinsCount = (int) ($wr[0] ?? 0);
    $wheelCoinsAwarded = (int) ($wr[1] ?? 0);
} catch (Throwable $e) {
    
}

$series = [];
$maxSeriesDays = 62;
$spanDays = max(1, (int) ceil(($to - $from + 1) / 86400));
$seriesDays = min($maxSeriesDays, $spanDays);
$seriesStart = $from + ($spanDays - $seriesDays) * 86400;

for ($i = 0; $i < $seriesDays; $i++) {
    $t = $seriesStart + $i * 86400;
    $dayEnd = min($t + 86400 - 1, $to);

    $st = $pdo->prepare(
        'SELECT COUNT(*) FROM users WHERE created_at >= :a AND created_at <= :b'
    );
    $st->execute([':a' => $t, ':b' => $dayEnd]);
    $nu = (int) $st->fetchColumn();

    $st = $pdo->prepare(
        'SELECT COUNT(*) FROM users WHERE last_login_at IS NOT NULL AND last_login_at >= :a AND last_login_at <= :b'
    );
    $st->execute([':a' => $t, ':b' => $dayEnd]);
    $lg = (int) $st->fetchColumn();

    $st = $pdo->prepare(
        'SELECT COUNT(*) FROM users WHERE last_seen_at IS NOT NULL AND last_seen_at >= :a AND last_seen_at <= :b'
    );
    $st->execute([':a' => $t, ':b' => $dayEnd]);
    $ac = (int) $st->fetchColumn();

    $st = $pdo->prepare(
        'SELECT COUNT(*) FROM purchases WHERE created_at >= :a AND created_at <= :b'
    );
    $st->execute([':a' => $t, ':b' => $dayEnd]);
    $pc = (int) $st->fetchColumn();

    $series[] = [
        'dayStart' => $t,
        'newUsers' => $nu,
        'logins' => $lg,
        'active' => $ac,
        'purchases' => $pc,
    ];
}

require_once __DIR__ . '/click_analytics_lib.php';

header('Content-Type: application/json; charset=utf-8');
echo json_encode(
    [
        'ok' => true,
        'generatedAt' => time(),
        'from' => $from,
        'to' => $to,
        'totalUsers' => $totalUsers,
        'newUsersInRange' => $newUsersInRange,
        'loginsInRange' => $loginsInRange,
        'activeInRange' => $activeInRange,
        'activeLast24h' => $activeLast24h,
        'purchasesCount' => $purchasesCount,
        'purchasesCoinsSum' => $purchasesCoinsSum,
        'totalCoinsSum' => $totalCoinsSum,
        'usersActiveAccount' => $usersActiveAccount,
        'usersInactiveAccount' => $usersInactiveAccount,
        'usersNeverLoggedIn' => $usersNeverLoggedIn,
        'purchasesByStatus' => $purchasesByStatus,
        'complaintsInRange' => $complaintsInRange,
        'complaintsByStatus' => $complaintsByStatus,
        'wheelSpinsCount' => $wheelSpinsCount,
        'wheelCoinsAwarded' => $wheelCoinsAwarded,
        'clickStats' => [
            'sponsors' => mocker_click_analytics_top($pdo, 'sponsor', $from, $to, 12),
            'bonuses' => mocker_click_analytics_top($pdo, 'bonus', $from, $to, 12),
            'promos' => mocker_click_analytics_top($pdo, 'promo', $from, $to, 12),
        ],
        'series' => $series,
    ],
    JSON_UNESCAPED_UNICODE
);
