<?php
declare(strict_types=1);

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

mocker_admin_require_login();

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

/** @return array{ageSec: int, ageHours: int, sla: string} */
function mocker_admin_pending_sla(int $createdAt, int $now): array
{
    $ageSec = max(0, $now - max(0, $createdAt));
    $ageHours = (int) floor($ageSec / 3600);
    $sla = 'ok';
    if ($ageHours >= 72) {
        $sla = 'critical';
    } elseif ($ageHours >= 24) {
        $sla = 'warn';
    }

    return ['ageSec' => $ageSec, 'ageHours' => $ageHours, 'sla' => $sla];
}

/**
 * @param array<int, array<string, mixed>> $items
 */
function mocker_admin_alert_add(array &$items, array $row, string $type, string $title, string $message, string $tab, int $now): void
{
    $createdAt = (int) ($row['created_at'] ?? 0);
    $slaMeta = mocker_admin_pending_sla($createdAt, $now);
    $items[] = [
        'id' => isset($row['id']) ? (int) $row['id'] : 0,
        'type' => $type,
        'title' => $title,
        'message' => $message,
        'tab' => $tab,
        'createdAt' => $createdAt,
        'ageSec' => $slaMeta['ageSec'],
        'ageHours' => $slaMeta['ageHours'],
        'sla' => $slaMeta['sla'],
    ];
}

/**
 * @return array{oldestAt: int|null, oldestAgeHours: int, sla: string}
 */
function mocker_admin_section_sla_from_oldest(?int $oldestAt, int $now): array
{
    if ($oldestAt === null || $oldestAt <= 0) {
        return ['oldestAt' => null, 'oldestAgeHours' => 0, 'sla' => 'ok'];
    }
    $meta = mocker_admin_pending_sla($oldestAt, $now);

    return [
        'oldestAt' => $oldestAt,
        'oldestAgeHours' => $meta['ageHours'],
        'sla' => $meta['sla'],
    ];
}

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

$now = time();
$sections = [];
$items = [];

if (mocker_admin_can('market-requests')) {
    $cnt = 0;
    $oldestAt = null;
    try {
        $st = $pdo->query("SELECT COUNT(*) FROM purchases WHERE COALESCE(status, 'pending') = 'pending'");
        $cnt = (int) $st->fetchColumn();
        $st = $pdo->query(
            "SELECT MIN(created_at) FROM purchases WHERE COALESCE(status, 'pending') = 'pending'"
        );
        $oldestRaw = $st->fetchColumn();
        $oldestAt = $oldestRaw !== false && $oldestRaw !== null ? (int) $oldestRaw : null;
    } catch (Throwable $e) {
        $cnt = 0;
    }
    $slaSec = mocker_admin_section_sla_from_oldest($oldestAt, $now);
    $sections[] = array_merge(
        ['key' => 'market-requests', 'label' => 'Market talepleri', 'count' => $cnt, 'tab' => 'market-requests'],
        $slaSec
    );
    if ($cnt > 0) {
        try {
            $st = $pdo->query(
                "SELECT p.id, p.created_at, p.item_title, COALESCE(u.username, 'Üye') AS username
                 FROM purchases p
                 LEFT JOIN users u ON u.id = p.user_id
                 WHERE COALESCE(p.status, 'pending') = 'pending'
                 ORDER BY p.created_at ASC, p.id ASC
                 LIMIT 20"
            );
            foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) {
                $user = trim((string) ($r['username'] ?? 'Üye'));
                $item = trim((string) ($r['item_title'] ?? 'Ürün'));
                mocker_admin_alert_add($items, $r, 'market-request', 'Market talebi', "{$user} · {$item}", 'market-requests', $now);
            }
        } catch (Throwable $e) {
            /* ignore */
        }
    }
}

if (mocker_admin_can('tickets')) {
    $cnt = 0;
    $oldestAt = null;
    try {
        $st = $pdo->query(
            "SELECT COUNT(*)
             FROM ticket_requests r
             INNER JOIN ticket_events e ON e.id = r.event_id
             WHERE r.status = 'pending' AND e.category = 'ticket'"
        );
        $cnt = (int) $st->fetchColumn();
        $st = $pdo->query(
            "SELECT MIN(r.created_at)
             FROM ticket_requests r
             INNER JOIN ticket_events e ON e.id = r.event_id
             WHERE r.status = 'pending' AND e.category = 'ticket'"
        );
        $oldestRaw = $st->fetchColumn();
        $oldestAt = $oldestRaw !== false && $oldestRaw !== null ? (int) $oldestRaw : null;
    } catch (Throwable $e) {
        $cnt = 0;
    }
    $slaSec = mocker_admin_section_sla_from_oldest($oldestAt, $now);
    $sections[] = array_merge(
        ['key' => 'tickets', 'label' => 'Bilet talepleri', 'count' => $cnt, 'tab' => 'tickets'],
        $slaSec
    );
    if ($cnt > 0) {
        try {
            $st = $pdo->query(
                "SELECT r.id, r.created_at, r.username, e.title
                 FROM ticket_requests r
                 INNER JOIN ticket_events e ON e.id = r.event_id
                 WHERE r.status = 'pending' AND e.category = 'ticket'
                 ORDER BY r.created_at ASC, r.id ASC
                 LIMIT 20"
            );
            foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) {
                $user = trim((string) ($r['username'] ?? 'Üye'));
                $ev = trim((string) ($r['title'] ?? 'Bilet etkinliği'));
                mocker_admin_alert_add($items, $r, 'ticket-request', 'Bilet talebi', "{$user} · {$ev}", 'tickets', $now);
            }
        } catch (Throwable $e) {
            /* ignore */
        }
    }
}

if (mocker_admin_can('events')) {
    $cnt = 0;
    $oldestAt = null;
    try {
        $st = $pdo->query(
            "SELECT COUNT(*)
             FROM ticket_requests r
             INNER JOIN ticket_events e ON e.id = r.event_id
             WHERE r.status = 'pending' AND e.category IN ('event', 'campaign')"
        );
        $cnt = (int) $st->fetchColumn();
        $st = $pdo->query(
            "SELECT MIN(r.created_at)
             FROM ticket_requests r
             INNER JOIN ticket_events e ON e.id = r.event_id
             WHERE r.status = 'pending' AND e.category IN ('event', 'campaign')"
        );
        $oldestRaw = $st->fetchColumn();
        $oldestAt = $oldestRaw !== false && $oldestRaw !== null ? (int) $oldestRaw : null;
    } catch (Throwable $e) {
        $cnt = 0;
    }
    $slaSec = mocker_admin_section_sla_from_oldest($oldestAt, $now);
    $sections[] = array_merge(
        ['key' => 'events', 'label' => 'Etkinlik talepleri', 'count' => $cnt, 'tab' => 'site-events'],
        $slaSec
    );
    if ($cnt > 0) {
        try {
            $st = $pdo->query(
                "SELECT r.id, r.created_at, r.username, e.title
                 FROM ticket_requests r
                 INNER JOIN ticket_events e ON e.id = r.event_id
                 WHERE r.status = 'pending' AND e.category IN ('event', 'campaign')
                 ORDER BY r.created_at ASC, r.id ASC
                 LIMIT 20"
            );
            foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) {
                $user = trim((string) ($r['username'] ?? 'Üye'));
                $ev = trim((string) ($r['title'] ?? 'Etkinlik'));
                mocker_admin_alert_add($items, $r, 'event-request', 'Etkinlik talebi', "{$user} · {$ev}", 'site-events', $now);
            }
        } catch (Throwable $e) {
            /* ignore */
        }
    }
}

if (mocker_admin_can('complaints')) {
    $cnt = 0;
    $oldestAt = null;
    try {
        $st = $pdo->query("SELECT COUNT(*) FROM complaints WHERE COALESCE(status, 'pending') = 'pending'");
        $cnt = (int) $st->fetchColumn();
        $st = $pdo->query(
            "SELECT MIN(created_at) FROM complaints WHERE COALESCE(status, 'pending') = 'pending'"
        );
        $oldestRaw = $st->fetchColumn();
        $oldestAt = $oldestRaw !== false && $oldestRaw !== null ? (int) $oldestRaw : null;
    } catch (Throwable $e) {
        $cnt = 0;
    }
    $slaSec = mocker_admin_section_sla_from_oldest($oldestAt, $now);
    $sections[] = array_merge(
        ['key' => 'complaints', 'label' => 'Şikayetler', 'count' => $cnt, 'tab' => 'complaints'],
        $slaSec
    );
    if ($cnt > 0) {
        try {
            $st = $pdo->query(
                "SELECT id, created_at, username, category
                 FROM complaints
                 WHERE COALESCE(status, 'pending') = 'pending'
                 ORDER BY created_at ASC, id ASC
                 LIMIT 20"
            );
            foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) {
                $user = trim((string) ($r['username'] ?? 'Üye'));
                $cat = trim((string) ($r['category'] ?? 'şikayet'));
                mocker_admin_alert_add($items, $r, 'complaint', 'Şikayet', "{$user} · {$cat}", 'complaints', $now);
            }
        } catch (Throwable $e) {
            /* ignore */
        }
    }
}

if (mocker_admin_can('affiliate-requests')) {
    $cnt = 0;
    $oldestAt = null;
    try {
        $st = $pdo->query("SELECT COUNT(*) FROM affiliate_requests WHERE COALESCE(status, 'pending') = 'pending'");
        $cnt = (int) $st->fetchColumn();
        $st = $pdo->query(
            "SELECT MIN(created_at) FROM affiliate_requests WHERE COALESCE(status, 'pending') = 'pending'"
        );
        $oldestRaw = $st->fetchColumn();
        $oldestAt = $oldestRaw !== false && $oldestRaw !== null ? (int) $oldestRaw : null;
    } catch (Throwable $e) {
        $cnt = 0;
    }
    $slaSec = mocker_admin_section_sla_from_oldest($oldestAt, $now);
    $sections[] = array_merge(
        ['key' => 'affiliate-requests', 'label' => 'Affiliate talepleri', 'count' => $cnt, 'tab' => 'affiliate-requests'],
        $slaSec
    );
    if ($cnt > 0) {
        try {
            $st = $pdo->query(
                "SELECT id, created_at, username, sponsor_title
                 FROM affiliate_requests
                 WHERE COALESCE(status, 'pending') = 'pending'
                 ORDER BY created_at ASC, id ASC
                 LIMIT 20"
            );
            foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) {
                $user = trim((string) ($r['username'] ?? 'Üye'));
                $sponsor = trim((string) ($r['sponsor_title'] ?? 'Sponsor'));
                mocker_admin_alert_add($items, $r, 'affiliate-request', 'Affiliate talebi', "{$user} · {$sponsor}", 'affiliate-requests', $now);
            }
        } catch (Throwable $e) {
            /* ignore */
        }
    }
}

usort(
    $items,
    static function (array $a, array $b): int {
        $slaOrder = ['critical' => 0, 'warn' => 1, 'ok' => 2];
        $sa = $slaOrder[$a['sla'] ?? 'ok'] ?? 2;
        $sb = $slaOrder[$b['sla'] ?? 'ok'] ?? 2;
        if ($sa !== $sb) {
            return $sa <=> $sb;
        }

        return (int) ($a['createdAt'] ?? 0) <=> (int) ($b['createdAt'] ?? 0);
    }
);
$items = array_slice($items, 0, 60);

$totalPending = 0;
$criticalCount = 0;
$warnCount = 0;
foreach ($sections as $sec) {
    $totalPending += max(0, (int) ($sec['count'] ?? 0));
    if (($sec['sla'] ?? '') === 'critical') {
        $criticalCount += max(0, (int) ($sec['count'] ?? 0));
    } elseif (($sec['sla'] ?? '') === 'warn') {
        $warnCount += max(0, (int) ($sec['count'] ?? 0));
    }
}

echo json_encode(
    [
        'ok' => true,
        'totalPending' => $totalPending,
        'criticalCount' => $criticalCount,
        'warnCount' => $warnCount,
        'sections' => $sections,
        'items' => $items,
        'serverTime' => $now,
        'slaRules' => [
            'warnHours' => 24,
            'criticalHours' => 72,
        ],
    ],
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
