<?php
/**
 * API Dashboard Stats - POINTAGES (GGR Web App)
 * Supporte action=stats (défaut) et action=detail&card_type=xxx
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . '/../../../config/database.php';

$date_debut = isset($_GET['date_debut']) ? trim($_GET['date_debut']) : date('Y-m-01');
$date_fin   = isset($_GET['date_fin'])   ? trim($_GET['date_fin'])   : date('Y-m-t');
$action     = isset($_GET['action'])     ? trim($_GET['action'])     : 'stats';
$card_type  = isset($_GET['card_type'])  ? trim($_GET['card_type'])  : '';

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_debut)) $date_debut = date('Y-m-01');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_fin))   $date_fin   = date('Y-m-t');

try {
    $db = Database::getInstance('transubd_PointageBus');
    $d1 = $date_debut;
    $d2 = $date_fin;

    if ($action === 'detail') {
        // Retourner le détail selon le type de carte
        $rows = [];
        $columns = [];
        $title = '';

        switch ($card_type) {
            case 'bus_disponible':
            case 'bus_absent':
            case 'taxi_disponible':
            case 'taxi_absent':
            case 'total_parc':
            case 'total_absent':
                if (strpos($card_type, 'bus') !== false) { $type = ['Bus', 'BusGL']; $title = 'Bus'; }
                elseif (strpos($card_type, 'taxi') !== false) { $type = ['Taxi']; $title = 'Taxis'; }
                else { $type = ['Bus', 'BusGL', 'Taxi']; $title = 'Total Parc'; }

                $title .= (strpos($card_type, 'disponible') !== false || strpos($card_type, 'parc') !== false) ? ' Disponibles' : ' Absents';
                $columns = ['Code Bus', 'Opérateur', 'Matricule'];
                
                $where = "WHERE 1=1";
                if ($type) {
                    $type_str = "'" . implode("','", $type) . "'";
                    $where .= " AND b.type IN ($type_str)";
                }
                $where .= " AND b.actif = 1";
                
                if (strpos($card_type, 'absent') !== false) {
                    $where .= " AND b.id NOT IN (SELECT DISTINCT c.bus_id FROM checkins c WHERE c.checkin_date BETWEEN ? AND ?)";
                    $params = [$d1, $d2];
                } else {
                    $params = [];
                }

                $rows = $db->select("
                    SELECT b.code_bus, COALESCE(o.name, 'N/A') as operateur, b.matricule
                    FROM buses b
                    LEFT JOIN operators o ON b.id_operateur = o.id
                    $where
                    ORDER BY b.code_bus
                ", $params);
                break;

            case 'bus_pointer':
            case 'taxi_pointer':
            case 'total_pointer':
                if ($card_type === 'bus_pointer') { $type = ['Bus', 'BusGL']; $title = 'Bus Pointés'; }
                elseif ($card_type === 'taxi_pointer') { $type = ['Taxi']; $title = 'Taxis Pointés'; }
                else { $type = ['Bus', 'BusGL', 'Taxi']; $title = 'Total Parc Pointé'; }

                $columns = ['Code Bus', 'Opérateur', 'Matricule', 'Nb Passages'];
                $where = "WHERE c.checkin_date BETWEEN ? AND ?";
                if ($type) {
                    $type_str = "'" . implode("','", $type) . "'";
                    $where .= " AND b.type IN ($type_str)";
                }

                $rows = $db->select("
                    SELECT b.code_bus, COALESCE(o.name, 'N/A') as operateur, b.matricule,
                           COUNT(c.id) as nb_passages
                    FROM checkins c
                    INNER JOIN buses b ON b.id = c.bus_id
                    LEFT JOIN operators o ON b.id_operateur = o.id
                    $where
                    GROUP BY b.id, b.code_bus, o.name, b.matricule
                    ORDER BY b.code_bus
                ", [$d1, $d2]);
                break;

            case 'bus_rotation':
            case 'taxi_rotation':
            case 'total_rotation':
                if ($card_type === 'bus_rotation') { $type = ['Bus', 'BusGL']; $title = 'Bus Rotations'; }
                elseif ($card_type === 'taxi_rotation') { $type = ['Taxi']; $title = 'Taxis Rotations'; }
                else { $type = ['Bus', 'BusGL', 'Taxi']; $title = 'Total Rotations'; }

                $columns = ['Code Bus', 'Opérateur', 'Matricule'];
                $where = "WHERE c.checkin_date BETWEEN ? AND ?";
                if ($type) {
                    $type_str = "'" . implode("','", $type) . "'";
                    $where .= " AND b.type IN ($type_str)";
                }

                $rows = $db->select("
                    SELECT b.code_bus, COALESCE(o.name, 'N/A') as operateur, b.matricule
                    FROM checkins c
                    INNER JOIN buses b ON b.id = c.bus_id
                    LEFT JOIN operators o ON b.id_operateur = o.id
                    $where
                    ORDER BY c.checkin_date DESC, c.checkin_time DESC, b.code_bus
                ", [$d1, $d2]);
                break;

            default:
                echo json_encode(['success' => false, 'message' => 'Type de carte invalide: ' . $card_type]);
                exit;
        }

        echo json_encode([
            'success'    => true,
            'title'      => $title,
            'columns'    => $columns,
            'data'       => $rows,
            'date_debut' => $d1,
            'date_fin'   => $d2,
        ]);
        exit;
    }

    // === Action stats (défaut) ===

    // Bus Disponible (Bus + BusGL)
    $row = $db->selectOne("SELECT COUNT(*) as cnt FROM buses WHERE type IN ('Bus', 'BusGL') AND actif=1");
    $bus_disponible = (int)($row['cnt'] ?? 0);

    // Bus Pointé (sans doublons) - Bus + BusGL
    $row = $db->selectOne("
        SELECT COUNT(DISTINCT c.bus_id) as cnt
        FROM checkins c
        INNER JOIN buses b ON b.id = c.bus_id AND b.type IN ('Bus', 'BusGL')
        WHERE DATE(c.checkin_date) BETWEEN ? AND ?
    ", [$d1, $d2]);
    $bus_pointer = (int)($row['cnt'] ?? 0);

    // Bus Rotation (avec doublons) - Bus + BusGL
    $row = $db->selectOne("
        SELECT COUNT(c.bus_id) as cnt
        FROM checkins c
        INNER JOIN buses b ON b.id = c.bus_id AND b.type IN ('Bus', 'BusGL')
        WHERE DATE(c.checkin_date) BETWEEN ? AND ?
    ", [$d1, $d2]);
    $bus_rotation = (int)($row['cnt'] ?? 0);

    $bus_absent = max(0, $bus_disponible - $bus_pointer);

    // Taxi Disponible
    $row = $db->selectOne("SELECT COUNT(*) as cnt FROM buses WHERE type='Taxi' AND actif=1");
    $taxi_disponible = (int)($row['cnt'] ?? 0);

    // Taxi Pointé
    $row = $db->selectOne("
        SELECT COUNT(DISTINCT c.bus_id) as cnt
        FROM checkins c
        INNER JOIN buses b ON b.id = c.bus_id AND b.type = 'Taxi'
        WHERE DATE(c.checkin_date) BETWEEN ? AND ?
    ", [$d1, $d2]);
    $taxi_pointer = (int)($row['cnt'] ?? 0);

    // Taxi Rotation
    $row = $db->selectOne("
        SELECT COUNT(c.bus_id) as cnt
        FROM checkins c
        INNER JOIN buses b ON b.id = c.bus_id AND b.type = 'Taxi'
        WHERE DATE(c.checkin_date) BETWEEN ? AND ?
    ", [$d1, $d2]);
    $taxi_rotation = (int)($row['cnt'] ?? 0);

    $taxi_absent = max(0, $taxi_disponible - $taxi_pointer);

    echo json_encode([
        'success' => true,
        'data' => [
            'bus_disponible' => $bus_disponible,
            'bus_pointer'    => $bus_pointer,
            'bus_rotation'   => $bus_rotation,
            'bus_absent'     => $bus_absent,
            'taxi_disponible'=> $taxi_disponible,
            'taxi_pointer'   => $taxi_pointer,
            'taxi_rotation'  => $taxi_rotation,
            'taxi_absent'    => $taxi_absent,
            // Nouveaux Totaux
            'total_parc'     => $bus_disponible + $taxi_disponible,
            'total_pointe'   => $bus_pointer + $taxi_pointer,
            'total_rotation' => $bus_rotation + $taxi_rotation,
            'total_absent'   => $bus_absent + $taxi_absent,
        ],
        'params' => ['date_debut' => $d1, 'date_fin' => $d2]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur: ' . $e->getMessage()]);
}