<?php
/**
 * NestSync — admin dashboard for the NeST OCDS sync jobs.
 * Displays last runs, per-run counts, skipped URLs, and quick stats over crm_nest_tenders.
 */
class NestSyncController extends Controller
{
    public function indexAction()
    {
        $db = new DB();
        $nt = new NestTenders();

        $totals = $db->mySelect(
            "SELECT COUNT(*) AS total,
                    SUM(CASE WHEN tender_end IS NOT NULL AND tender_end > NOW() THEN 1 ELSE 0 END) AS open_now,
                    SUM(CASE WHEN linked_project_id IS NOT NULL THEN 1 ELSE 0 END) AS linked,
                    SUM(CASE WHEN linked_tender_id  IS NOT NULL THEN 1 ELSE 0 END) AS tracked,
                    MAX(last_synced_at) AS last_synced
               FROM crm_nest_tenders",
            []
        )[0] ?? [];

        $lastRun = $db->mySelect(
            "SELECT * FROM crm_nest_sync_log ORDER BY started_at DESC LIMIT 1",
            []
        )[0] ?? null;

        $byFy = $db->mySelect(
            "SELECT financial_year, COUNT(*) n FROM crm_nest_tenders
              WHERE financial_year IS NOT NULL GROUP BY financial_year ORDER BY financial_year DESC LIMIT 6",
            []
        ) ?: [];

        $byCat = $db->mySelect(
            "SELECT category_acronym, COUNT(*) n FROM crm_nest_tenders
              WHERE category_acronym IS NOT NULL GROUP BY category_acronym ORDER BY n DESC",
            []
        ) ?: [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('NestSync/index', [
            'page_title' => 'NeST Sync · Admin',
            'totals'     => $totals,
            'last_run'   => $lastRun,
            'runs'       => $nt->recentSyncLogs(30),
            'by_fy'      => $byFy,
            'by_cat'     => $byCat,
        ]);
    }
}
