<?php
// app/model/api/inscriptions.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
require_once __DIR__ . '/../service/InscriptionConcoursService.php';
require_once __DIR__ . '/../service/UtilService.php';
$service = new InscriptionConcoursService();
$action = $_REQUEST['action'] ?? $_GET['action'] ?? $_POST['action'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];



if ($action === 'download_doc') {
    if (isset($_REQUEST['id'])) {
        $service->downloadAllCandidatDocs(intval($_REQUEST['id']));
        exit;
    } else {
        echo json_encode(['success' => false, 'message' => 'ID requis']);
        exit;
    }
}
try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'types_diplome':
                    $data = $service->getAllTypeDiplome();
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;
                case 'list':
                    $data = $service->getAllWithDetails();
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;

                case 'grouped':
                    $data = $service->getGroupedByTypeDiplome();
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;

                case 'by_type':
                    if (isset($_GET['type_id'])) {
                        $data = $service->getByTypeDiplome($_GET['type_id']);
                        echo json_encode(['success' => true, 'data' => $data]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'type_id requis']);
                    }
                    break;

                case 'get':
                    if (isset($_GET['id'])) {
                        $data = $service->getInscriptionWithDetails($_GET['id']);
                        if ($data) {
                            echo json_encode(['success' => true, 'data' => $data]);
                        } else {
                            echo json_encode(['success' => false, 'message' => 'Inscription non trouvée']);
                        }
                    } else {
                        echo json_encode(['success' => false, 'message' => 'ID requis']);
                    }
                    break;

                case 'stats':
                    $data = $service->getStats();
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;

                case 'concours':
                    $data = $service->getAllConcours();
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;

                case 'candidats':
                    $data = $service->getAllCandidats();
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;

                case 'export_sample_avant_ecrit':
                    if (isset($_GET['concours_id']) && !empty($_GET['concours_id'])) {
                        $data = $service->getCandidatsForAvantEcritSample($_GET['concours_id']);
                        echo json_encode(['success' => true, 'data' => $data]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'concours_id requis']);
                    }
                    break;

                case 'export_sample_avant_orale':
                    if (isset($_GET['concours_id']) && !empty($_GET['concours_id'])) {
                        $data = $service->getCandidatsForAvantOraleSample($_GET['concours_id']);
                        echo json_encode(['success' => true, 'data' => $data]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'concours_id requis']);
                    }
                    break;

                case 'export_sample_avant_finale':
                    if (isset($_GET['concours_id']) && !empty($_GET['concours_id'])) {
                        $data = $service->getCandidatsForAvantFinaleSample($_GET['concours_id']);
                        echo json_encode(['success' => true, 'data' => $data]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'concours_id requis']);
                    }
                    break;

                case 'get_by_candidat':
                    if (isset($_GET['candidat_id'])) {
                        $data = $service->findInscriptionByCandidat($_GET['candidat_id']);
                        if ($data) {
                            echo json_encode(['success' => true, 'data' => $data, 'exists' => true]);
                        } else {
                            echo json_encode(['success' => false, 'data' => null, 'exists' => false, 'message' => 'Aucune inscription trouvée']);
                        }
                    } else {
                        echo json_encode(['success' => false, 'message' => 'candidat_id et concours_id requis']);
                    }
                    break;
                case 'get_by_candidat_and_concours':
                    if (isset($_GET['candidat_id']) && isset($_GET['concours_id'])) {
                        $data = $service->findInscriptionByCandidatAndConcours($_GET['candidat_id'], $_GET['concours_id']);
                        if ($data) {
                            echo json_encode(['success' => true, 'data' => $data, 'exists' => true]);
                        } else {
                            echo json_encode(['success' => false, 'data' => null, 'exists' => false, 'message' => 'Aucune inscription trouvée']);
                        }
                    } else {
                        echo json_encode(['success' => false, 'message' => 'candidat_id et concours_id requis']);
                    }
                    break;

                case 'get_types_by_concours':
                    if (isset($_GET['concours_id'])) {
                        $data = $service->getTypeDiplomeByConcours($_GET['concours_id']);
                        echo json_encode(['success' => true, 'data' => $data]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'concours_id requis']);
                    }
                    break;

                case 'get_by_id':
                    if (isset($_GET['id'])) {
                        $data = $service->getById($_GET['id']);
                        echo json_encode(['success' => true, 'data' => $data]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Id requis']);
                    }
                    break;

                case 'check_exists':
                    if (isset($_GET['candidat_id']) && isset($_GET['concours_id'])) {
                        $exists = $service->findInscriptionByCandidatAndConcours($_GET['candidat_id'], $_GET['concours_id']);
                        echo json_encode(['success' => true, 'exists' => $exists !== null, 'data' => $exists]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'candidat_id et concours_id requis']);
                    }
                    break;

                case 'search':
                    $filters = [
                        'candidat_search' => isset($_GET['candidat_search']) ? $_GET['candidat_search'] : '',
                        'code' => isset($_GET['code']) ? $_GET['code'] : '',
                        'label' => isset($_GET['label']) ? $_GET['label'] : '',
                        'concours_id' => isset($_GET['concours_id']) ? $_GET['concours_id'] : '',
                        'type_diplome_id' => isset($_GET['type_diplome_id']) ? $_GET['type_diplome_id'] : '',
                        'etat_inscription' => isset($_GET['etat_inscription']) ? $_GET['etat_inscription'] : '',
                        'resultat_inscription' => isset($_GET['resultat_inscription']) ? $_GET['resultat_inscription'] : '',
                        'active' => isset($_GET['active']) ? $_GET['active'] : '',
                        'page' => isset($_GET['page']) ? (int)$_GET['page'] : 1,
                        'per_page' => isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10,
                        'singlePage' => isset($_GET['singlePage']) ? (bool)$_GET['singlePage'] : false,
                        'dataMode' => isset($_GET['dataMode']) ? $_GET['dataMode'] : ''
                    ];
                    $data = $service->search($filters);
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;

                case 'download':
                    try {
                        $filterType = isset($_GET['filter']) ? $_GET['filter'] : 'ALL';
                        $filters = $_GET;
                        unset($filters['action']);
                        unset($filters['filter']);
                        $dataMode = isset($filters['dataMode']) ? $filters['dataMode'] : '';

                        $result = $service->download($filters, $filterType, $dataMode);

                        if ($result['success']) {
                            echo json_encode([
                                'success' => true,
                                'data' => $result['data'],
                                'count' => $result['count'],
                                'filter' => $result['filter']
                            ]);
                        } else {
                            echo json_encode([
                                'success' => false,
                                'message' => $result['message']
                            ]);
                        }
                    } catch (Exception $e) {
                        echo json_encode([
                            'success' => false,
                            'message' => 'Erreur serveur: ' . $e->getMessage()
                        ]);
                    }
                    break;

                case 'download_template':
                    $templatePath = __DIR__ . '/../ressources/ISTWI-2026-mini.csv';

                    if (!file_exists($templatePath)) {
                        echo json_encode(['success' => false, 'message' => 'Fichier template non trouvé.']);
                        exit;
                    }

                    if (isset($_GET['download']) && $_GET['download'] === 'true') {
                        header('Content-Type: text/csv');
                        header('Content-Disposition: attachment; filename="template_import_inscriptions.csv"');
                        header('Content-Length: ' . filesize($templatePath));
                        header('Cache-Control: no-cache, must-revalidate');
                        header('Pragma: public');

                        readfile($templatePath);
                        exit;
                    }

                    $content = file_get_contents($templatePath);
                    echo json_encode([
                        'success' => true,
                        'data' => $content,
                        'filename' => 'template_import_inscriptions.csv'
                    ]);
                    break;
                case 'download_doc':
                    if (isset($_GET['id'])) {
                        $inscriptionId = intval($_GET['id']);
                        $service->downloadAllCandidatDocs($inscriptionId);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'ID requis']);
                        exit;
                    }
                    break;
                case 'download_all':
                    $id = $_GET['id'];
                    $candidat = $service->getCandidatById($id);

                    $zip = new ZipArchive();
                    $zipName = "Documents_" . $candidat['code_concours'] . ".zip";

                    if ($zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                        $files = [
                            'cv' => $candidat['cv_path'],
                            'diplome' => $candidat['diplome_path'],
                        ];

                        foreach ($files as $name => $path) {
                            if (file_exists($path)) {
                                $zip->addFile($path, $candidat['code_concours'] . "_" . $name . ".pdf");
                            }
                        }
                        $zip->close();
                        header('Content-Type: application/zip');
                        header('Content-Disposition: attachment; filename='.basename($zipName));
                        readfile($zipName);
                        unlink($zipName);
                    }
                    break;

                case 'download_all_concours_docs':
                    if (isset($_GET['concours_id'])) {
                        $concoursId = intval($_GET['concours_id']);
                        $filters = ['concours_id' => $concoursId, 'page' => 1, 'per_page' => 9999];
                        $inscriptions = $service->search($filters)['data'];

                        if (empty($inscriptions)) {  exit; }

                        $zip = new ZipArchive();
                        $zipPath = sys_get_temp_dir() . '/concours_' . $concoursId . '.zip';

                        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                            foreach ($inscriptions as $ins) {
                            }
                            $zip->close();
                            header('Content-Type: application/zip');
                            header('Content-Disposition: attachment; filename="documents_concours.zip"');
                            readfile($zipPath);
                            unlink($zipPath);
                            exit;
                        }
                    }
                    break;

                default:
                    $data = $service->getAllWithDetails();
                    echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

        case 'POST':
            if ($action === 'import_notes') {
                if (!isset($_POST['concours_id']) || empty($_POST['concours_id'])) {
                    echo json_encode(['success' => false, 'message' => 'ID du concours manquant.']);
                    exit;
                }
                if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
                    echo json_encode(['success' => false, 'message' => 'Fichier CSV invalide ou manquant.']);
                    exit;
                }

                $concoursId = intval($_POST['concours_id']);
                $fileTmpPath = $_FILES['csv_file']['tmp_name'];

                $notesData = [];
                if (($handle = fopen($fileTmpPath, "r")) !== FALSE) {
                    while (($row = fgetcsv($handle, 1000, ";")) !== FALSE) {
                        if (count($row) >= 2) {
                            $cin = trim($row[0]);
                            $ecrit = (isset($row[1]) && trim($row[1]) !== '') ? floatval(trim($row[1])) : null;
                            $orale = (isset($row[2]) && trim($row[2]) !== '') ? floatval(trim($row[2])) : null;

                            if (!empty($cin)) {
                                $notesData[$cin] = [
                                    'ecrit' => $ecrit,
                                    'orale' => $orale
                                ];
                            }
                        }
                    }
                    fclose($handle);
                }

                $res = $service->importNotes($concoursId, $notesData);
                echo json_encode($res);
                exit;
            }

            if ($action === 'import_avant_ecrit') {
                if (!isset($_POST['concours_id']) || empty($_POST['concours_id'])) {
                    echo json_encode(['success' => false, 'message' => 'ID du concours manquant.']);
                    exit;
                }
                if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
                    echo json_encode(['success' => false, 'message' => 'Fichier CSV invalide ou manquant.']);
                    exit;
                }

                $fileType = pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION);
                if (strtolower($fileType) !== 'csv') {
                    echo json_encode(['success' => false, 'message' => 'Le fichier doit être au format CSV.']);
                    exit;
                }

                $concoursId = intval($_POST['concours_id']);
                $fileTmpPath = $_FILES['csv_file']['tmp_name'];

                $notesData = [];
                if (($handle = fopen($fileTmpPath, "r")) !== FALSE) {
                    $rowIndex = 0;
                    while (($row = fgetcsv($handle, 1000, ";")) !== FALSE) {
                        $rowIndex++;
                        // Ignorer la ligne d'en-tête si présente (ex: CIN;moyenne_calcule_avant_ecrit)
                        if ($rowIndex === 1 && isset($row[0]) && stripos($row[0], 'CIN') !== false) {
                            continue;
                        }
                        if (count($row) >= 2) {
                            $cin = trim($row[0]);
                            $avantEcrit = (isset($row[1]) && trim($row[1]) !== '') ? floatval(trim($row[1])) : null;

                            if (!empty($cin) && $avantEcrit !== null) {
                                $notesData[$cin] = $avantEcrit;
                            }
                        }
                    }
                    fclose($handle);
                }

                if (empty($notesData)) {
                    echo json_encode(['success' => false, 'message' => 'Aucune donnée valide trouvée dans le fichier CSV.']);
                    exit;
                }

                $res = $service->importAvantEcrit($concoursId, $notesData);
                echo json_encode($res);
                exit;
            }

            if ($action === 'import_ecrit_avant_orale') {
                if (!isset($_POST['concours_id']) || empty($_POST['concours_id'])) {
                    echo json_encode(['success' => false, 'message' => 'ID du concours manquant.']);
                    exit;
                }
                if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
                    echo json_encode(['success' => false, 'message' => 'Fichier CSV invalide ou manquant.']);
                    exit;
                }

                $fileType = pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION);
                if (strtolower($fileType) !== 'csv') {
                    echo json_encode(['success' => false, 'message' => 'Le fichier doit être au format CSV.']);
                    exit;
                }

                $concoursId = intval($_POST['concours_id']);
                $fileTmpPath = $_FILES['csv_file']['tmp_name'];

                $notesData = [];
                if (($handle = fopen($fileTmpPath, "r")) !== FALSE) {
                    $rowIndex = 0;
                    while (($row = fgetcsv($handle, 1000, ";")) !== FALSE) {
                        $rowIndex++;
                        // Ignorer la ligne d'en-tête si présente (ex: CIN;moyenne_ecrit;moyenne_calcule_avant_orale)
                        if ($rowIndex === 1 && isset($row[0]) && stripos($row[0], 'CIN') !== false) {
                            continue;
                        }
                        if (count($row) >= 1) {
                            $cin = trim($row[0]);
                            $ecrit = (isset($row[1]) && trim($row[1]) !== '') ? floatval(trim($row[1])) : null;
                            $avantOrale = (isset($row[2]) && trim($row[2]) !== '') ? floatval(trim($row[2])) : null;

                            if (!empty($cin) && ($ecrit !== null || $avantOrale !== null)) {
                                $notesData[$cin] = [
                                    'ecrit' => $ecrit,
                                    'avant_orale' => $avantOrale
                                ];
                            }
                        }
                    }
                    fclose($handle);
                }

                if (empty($notesData)) {
                    echo json_encode(['success' => false, 'message' => 'Aucune donnée valide trouvée dans le fichier CSV.']);
                    exit;
                }

                $res = $service->importEcritAvantOrale($concoursId, $notesData);
                echo json_encode($res);
                exit;
            }

            if ($action === 'import_orale_avant_finale') {
                if (!isset($_POST['concours_id']) || empty($_POST['concours_id'])) {
                    echo json_encode(['success' => false, 'message' => 'ID du concours manquant.']);
                    exit;
                }
                if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
                    echo json_encode(['success' => false, 'message' => 'Fichier CSV invalide ou manquant.']);
                    exit;
                }

                $fileType = pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION);
                if (strtolower($fileType) !== 'csv') {
                    echo json_encode(['success' => false, 'message' => 'Le fichier doit être au format CSV.']);
                    exit;
                }

                $concoursId = intval($_POST['concours_id']);
                $fileTmpPath = $_FILES['csv_file']['tmp_name'];

                $notesData = [];
                if (($handle = fopen($fileTmpPath, "r")) !== FALSE) {
                    $rowIndex = 0;
                    while (($row = fgetcsv($handle, 1000, ";")) !== FALSE) {
                        $rowIndex++;
                        // Ignorer la ligne d'en-tête si présente (ex: CIN;moyenne_orale;moyenne_calcule_avant_finale)
                        if ($rowIndex === 1 && isset($row[0]) && stripos($row[0], 'CIN') !== false) {
                            continue;
                        }
                        if (count($row) >= 1) {
                            $cin = trim($row[0]);
                            $orale = (isset($row[1]) && trim($row[1]) !== '') ? floatval(trim($row[1])) : null;
                            $avantFinale = (isset($row[2]) && trim($row[2]) !== '') ? floatval(trim($row[2])) : null;

                            if (!empty($cin) && ($orale !== null || $avantFinale !== null)) {
                                $notesData[$cin] = [
                                    'orale' => $orale,
                                    'avant_finale' => $avantFinale
                                ];
                            }
                        }
                    }
                    fclose($handle);
                }

                if (empty($notesData)) {
                    echo json_encode(['success' => false, 'message' => 'Aucune donnée valide trouvée dans le fichier CSV.']);
                    exit;
                }

                $res = $service->importOraleAvantFinale($concoursId, $notesData);
                echo json_encode($res);
                exit;
            }

            $input = json_decode(file_get_contents('php://input'), true);

            if ($action === 'create_or_update') {
                if ($input && ((isset($input['candidat_id']) && isset($input['concours_id']) && $input['etat_inscription'] != 'BROUILLON') || (isset($input['candidat_id']) && isset($input['concours_id']) && $input['etat_inscription'] === 'BROUILLON'))) {
                    $result = $service->createOrUpdateInscription($input);
                    echo json_encode([
                        'success' => true,
                        'id' => $result['id'],
                        'candidat_id' => $input['candidat_id'],
                        'is_new' => $result['is_new'],
                        'message' => $result['is_new'] ? 'Inscription créée avec succès' : 'Inscription mise à jour avec succès'
                    ]);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'candidat_id et concours_id requis']);
                }
            } else if ($action === "import_csv") {
                if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
                    echo json_encode(['success' => false, 'message' => 'Fichier CSV invalide ou manquant.']);
                    exit;
                }

                if (!isset($_POST['concours_id']) || empty($_POST['concours_id'])) {
                    echo json_encode(['success' => false, 'message' => 'ID du concours manquant.']);
                    exit;
                }

                $concoursId = intval($_POST['concours_id']);
                $fileTmpPath = $_FILES['csv_file']['tmp_name'];
                $fileType = pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION);

                if (strtolower($fileType) !== 'csv') {
                    echo json_encode(['success' => false, 'message' => 'Le fichier doit être au format CSV.']);
                    exit;
                }

                $result = $service->importCsv($fileTmpPath, $concoursId);
                echo json_encode($result);

            } else if ($action == 'upload_documents') {
                if (!isset($_POST['candidat_id']) || !isset($_POST['concours_id']) || !isset($_POST['cin']) || !isset($_POST['inscription_id'])) {
                    echo json_encode(['success' => false, 'message' => 'Données manquantes']);
                    break;
                }

                $utilService = new \model\service\UtilService();

                $data = [
                    'candidat_id' => $_POST['candidat_id'],
                    'concours_id' => $_POST['concours_id'],
                    'cin' => $_POST['cin'],
                    'inscription_id' => $_POST['inscription_id']
                ];

                $result = $utilService->uploadDocuments($data, $_FILES);
                if ($result["success"] == true) {
                    $updateDate = $service->updateUpload($result["uploaded"], $_POST['inscription_id']);
                }
                echo json_encode($result);
            } else if ($action == 'batchUpdateResultat') {
                if ($input && isset($input['ids']) && isset($input['resultat_inscription'])) {
                    $result = $service->batchUpdateResultat($input['ids'], $input['resultat_inscription']);
                } else {
                    $result = ['success' => false, 'message' => 'Données invalides.'];
                }
                echo json_encode($result);
            } else {
                if ($input) {
                    $id = $service->createInscription($input);
                    echo json_encode(['success' => true, 'id' => $id, 'message' => 'Inscription créée avec succès']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Données invalides']);
                }
            }
            break;

        case 'PUT':
            if (isset($_GET['id'])) {
                $input = json_decode(file_get_contents('php://input'), true);
                if ($input) {
                    $service->updateInscription($_GET['id'], $input);
                    echo json_encode(['success' => true, 'message' => 'Inscription mise à jour avec succès']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Données invalides']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'ID requis']);
            }
            break;


        case 'DELETE':
            if (isset($_GET['id'])) {
                $service->deleteInscription($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Inscription supprimée avec succès']);
            } else {
                echo json_encode(['success' => false, 'message' => 'ID requis']);
            }
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Méthode non autorisée']);
    }
} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => 'Runtime Error: ' . $e->getMessage()]);
}