<?php
/**
 * API pour les versements Boumerdes (Version Distante)
 * À installer sur le serveur cPanel dans le dossier api/apiggr/
 */

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

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

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

$action = $_REQUEST['action'] ?? 'dashboard';

try {
    $db = Database::getInstance();

    switch ($action) {
        case 'dashboard':
            $date = $_GET['date'] ?? null;
            $date_start = $_GET['date_start'] ?? null;
            $date_end = $_GET['date_end'] ?? null;
            $month = $_GET['month'] ?? null;
            $quarter = $_GET['quarter'] ?? null;
            $semester = $_GET['semester'] ?? null;
            $year = $_GET['year'] ?? null;

            $dateCondition = "1=1";
            $params = [];

            if ($date) { $dateCondition = "DATE(date_vers) = ?"; $params[] = $date; }
            elseif ($date_start && $date_end) { $dateCondition = "DATE(date_vers) BETWEEN ? AND ?"; $params[] = $date_start; $params[] = $date_end; }
            elseif ($month) { $dateCondition = "MONTH(date_vers) = ? AND YEAR(date_vers) = ?"; $params[] = (int)$month; $params[] = (int)date('Y'); }
            elseif ($year) { $dateCondition = "YEAR(date_vers) = ?"; $params[] = (int)$year; }

            $busDisponible = $db->selectOne("SELECT COUNT(*) as count FROM buses WHERE type = 'Bus' AND actif = 1")['count'];
            $taxiDisponible = $db->selectOne("SELECT COUNT(*) as count FROM buses WHERE type = 'Taxi' AND actif = 1")['count'];

            $busVers = $db->selectOne("SELECT COUNT(*) as count FROM bons_vers WHERE type_vehicule = 'Bus' AND $dateCondition", $params)['count'];
            $taxiVers = $db->selectOne("SELECT COUNT(*) as count FROM bons_vers WHERE type_vehicule = 'Taxi' AND $dateCondition", $params)['count'];

            $busNonVers = max(0, $busDisponible - $busVers);
            $taxiNonVers = max(0, $taxiDisponible - $taxiVers);

            $montantEncaisse = $db->selectOne("SELECT SUM(mt_ttc) as total FROM bons_vers WHERE $dateCondition", $params)['total'] ?? 0;

            $tarifs = $db->select("SELECT type, ttc FROM tarifs");
            $tarifBus = 0; $tarifTaxi = 0;
            foreach ($tarifs as $tarif) {
                if ($tarif['type'] === 'Bus') $tarifBus = $tarif['ttc'];
                if ($tarif['type'] === 'Taxi') $tarifTaxi = $tarif['ttc'];
            }
            $montantNonEncaisse = ($busNonVers * $tarifBus) + ($taxiNonVers * $tarifTaxi);

            $annualStats = [];
            $currentYear = date('Y');
            for ($m = 1; $m <= 12; $m++) {
                $total = $db->selectOne("SELECT SUM(mt_ttc) as total FROM bons_vers WHERE MONTH(date_vers) = ? AND YEAR(date_vers) = ?", [$m, $currentYear])['total'] ?? 0;
                $annualStats[] = ['month' => sprintf('%04d-%02d', $currentYear, $m), 'total' => $total];
            }

            $queryList = "SELECT bv.*, bv.type_vehicule as type, COALESCE(bv.matricule, bv.operateur) as matricule, o.name as operateur_name, l.name as ligne FROM bons_vers bv LEFT JOIN buses b ON bv.matricule = b.matricule LEFT JOIN operators o ON b.id_operateur = o.id LEFT JOIN lignes l ON b.id_ligne = l.ligne_code WHERE $dateCondition ORDER BY bv.date_vers DESC";
            $versements = $db->select($queryList, $params);

            echo json_encode(['success' => true, 'message' => 'Data retrieved successfully', 'busDisponible' => (int)$busDisponible, 'taxiDisponible' => (int)$taxiDisponible, 'busVers' => (int)$busVers, 'taxiVers' => (int)$taxiVers, 'busNonVers' => (int)$busNonVers, 'taxiNonVers' => (int)$taxiNonVers, 'montantEncaisse' => (float)$montantEncaisse, 'montantNonEncaisse' => (float)$montantNonEncaisse, 'annualStats' => $annualStats, 'versements' => $versements]);
            break;

        case 'get_initial_data':
            $count = $db->selectOne("SELECT COUNT(*) as count FROM bons_vers")['count'];
            $num_bvr = "BVR" . str_pad($count + 1, 6, '0', STR_PAD_LEFT) . "-" . date('y');
            $types = $db->select("SELECT id, libelle FROM type_vehicule ORDER BY libelle");
            echo json_encode(['success' => true, 'num_bvr' => $num_bvr, 'types' => $types, 'system_date' => date('d/m/Y'), 'system_time' => date('H:i')]);
            break;

        case 'get_operators':
            $type_id = $_GET['type_id'] ?? '';
            $type_libelle = $db->selectOne("SELECT libelle FROM type_vehicule WHERE id = ?", [$type_id])['libelle'];
            $operators = $db->select("SELECT DISTINCT o.id, o.name FROM operators o INNER JOIN buses b ON o.id = b.id_operateur WHERE b.type = ? AND b.actif = 1 ORDER BY o.name", [$type_libelle]);
            echo json_encode(['success' => true, 'operators' => $operators]);
            break;

        case 'get_vehicles':
            $id_operateur = $_GET['id_operateur'] ?? '';
            $type_id = $_GET['type_id'] ?? '';
            $type_libelle = $db->selectOne("SELECT libelle FROM type_vehicule WHERE id = ?", [$type_id])['libelle'];
            $vehicles = $db->select("SELECT matricule FROM buses WHERE id_operateur = ? AND type = ? AND actif = 1 ORDER BY matricule", [$id_operateur, $type_libelle]);
            echo json_encode(['success' => true, 'vehicles' => $vehicles]);
            break;

        case 'get_tarifs':
            $tarifs = $db->select("SELECT * FROM tarifs");
            echo json_encode(['success' => true, 'tarifs' => $tarifs]);
            break;
            
        case 'save_versement':
            $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
            $date_vers = $input['date_vers'] ?? date('Y-m-d');
            $id_operateur = $input['id_operateur'] ?? '';
            $type_id = $input['type_id'] ?? '';
            $matricules = $input['matricules'] ?? [];

            if (empty($matricules)) throw new Exception("Aucun véhicule sélectionné");

            $nom_operateur = $db->selectOne("SELECT name FROM operators WHERE id = ?", [$id_operateur])['name'];
            $type_libelle = $db->selectOne("SELECT libelle FROM type_vehicule WHERE id = ?", [$type_id])['libelle'];
            $tarif = $db->selectOne("SELECT ttc FROM tarifs WHERE type = ?", [$type_libelle])['ttc'] ?? 0;
            
            $saved_records = [];
            foreach ($matricules as $matricule) {
                $count = $db->selectOne("SELECT COUNT(*) as count FROM bons_vers")['count'];
                $num_bvr = "BVR" . str_pad($count + 1, 6, '0', STR_PAD_LEFT) . "-" . date('y');
                $db->query("INSERT INTO bons_vers (num_bvr, date_vers, periode, operateur, type_vehicule, matricule, mt_ttc, observation, creer_par, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [$num_bvr, $date_vers, $input['periode_p'] ?? '', $nom_operateur, $type_libelle, $matricule, $tarif, $input['obs'] ?? '', $input['creer_par'] ?? 'System', $date_vers]);
                $saved_records[] = ['num_bvr' => $num_bvr, 'matricule' => $matricule, 'ttc' => $tarif];
            }
            echo json_encode(['success' => true, 'message' => 'Versements enregistrés avec succès', 'records' => $saved_records, 'count' => count($saved_records)]);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Action non reconnue: ' . $action]);
            break;
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Erreur: ' . $e->getMessage()]);
}
