<?php
// ─── GET /api/jobcards/stats.php ─────────────────────────────────────────
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

Auth::require();
$db = DB::get();

$now       = new DateTime();
$thisMonth = $now->format('Y-m');
$lastMonth = (clone $now)->modify('-1 month')->format('Y-m');

// Jobcard counts by month (using date_created)
$jc_this  = (int) $db->scalar(
    "SELECT COUNT(*) FROM jobcards WHERE DATE_FORMAT(date_created,'%Y-%m')=?", [$thisMonth]);
$jc_last  = (int) $db->scalar(
    "SELECT COUNT(*) FROM jobcards WHERE DATE_FORMAT(date_created,'%Y-%m')=?", [$lastMonth]);

// Active right now
$jc_active = (int) $db->scalar(
    "SELECT COUNT(*) FROM jobcards WHERE jc_current_status NOT IN ('COMPLETE') AND jc_current_status IS NOT NULL");

// Completed this month
$jc_completed_this = (int) $db->scalar(
    "SELECT COUNT(*) FROM jobcards WHERE jc_current_status='COMPLETE'
     AND DATE_FORMAT(date_time_closed,'%Y-%m')=?", [$thisMonth]);

Response::ok([
    'jc_this_month'         => $jc_this,
    'jc_last_month'         => $jc_last,
    'jc_active'             => $jc_active,
    'jc_completed_this'     => $jc_completed_this,
    'this_month_label'      => $now->format('M Y'),
    'last_month_label'      => (clone $now)->modify('-1 month')->format('M Y'),
]);