<?php
// (headers, connexion, lecture FormData ou JSON — pareil que précédemment)
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }
header("Content-Type: application/json");

$host="192.168.0.4"; $dbname="DemandeConge"; $username="wpuser"; $password="-2b/)ru5/Bi8P[7_";
$conn = new mysqli($host,$username,$password,$dbname);
if ($conn->connect_error) { echo json_encode(["success"=>false,"message"=>"Erreur DB: ".$conn->connect_error]); exit(); }

// Lecture JSON (support FormData via $_POST['data'])
if (isset($_POST['data'])) {
    $data = json_decode($_POST['data'], true);
} else {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
}
if ($data === null) {
    echo json_encode(["success"=>false,"message"=>"JSON invalide"]); $conn->close(); exit();
}

// Vérifs minimales
if (!isset($data['EmployeeId'],$data['DateDebut'],$data['DateFin'],$data['Repartition'],$data['NombreJours'])) {
    echo json_encode(["success"=>false,"message"=>"Données manquantes"]); $conn->close(); exit();
}

$employeeId = (int)$data['EmployeeId'];
$dateDebut  = $data['DateDebut'];
$dateFin    = $data['DateFin'];
$commentaire= $data['Commentaire'] ?? '';
$numDays    = (float)$data['NombreJours'];
$statut     = 'En attente';
$currentDate= date('Y-m-d H:i:s');

// 1) Construire la liste d'IDs pour TypeCongeId (CSV) (compatibilité)
$typeIds = [];
foreach ($data['Repartition'] as $rep) {
    $code = $rep['TypeConge']; // CP, RTT, ABS ou texte libre
    switch ($code) {
        case 'CP': $name = 'Congé payé'; break;
        case 'RTT': $name = 'RTT'; break;
        case 'ABS': $name = 'Congé maladie'; break;
        default: $name = $code; break;
    }
    $s = $conn->prepare("SELECT Id FROM TypeConge WHERE Nom = ?");
    $s->bind_param("s", $name);
    $s->execute();
    $res = $s->get_result();
    if ($r = $res->fetch_assoc()) $typeIds[] = $r['Id'];
    $s->close();
}
if (empty($typeIds)) { echo json_encode(["success"=>false,"message"=>"Aucun type valide"]); $conn->close(); exit(); }
$typeCongeIdCsv = implode(',', $typeIds);

// 2) Insertion unique dans DemandeConge
$insert = $conn->prepare("INSERT INTO DemandeConge (EmployeeId, DateDebut, DateFin, TypeCongeId, Statut, DateDemande, Commentaire, Validateur, NombreJours) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$validParam = '';
$insert->bind_param("isssssssd", $employeeId, $dateDebut, $dateFin, $typeCongeIdCsv, $statut, $currentDate, $commentaire, $validParam, $numDays);
if (!$insert->execute()) {
    echo json_encode(["success"=>false,"message"=>"Erreur insert DemandeConge: ".$insert->error]);
    $insert->close(); $conn->close(); exit();
}
$demandeId = $conn->insert_id;
$insert->close();

// 3) INSÉRER la répartition réelle dans DemandeCongeType (une ligne par type)
$insertType = $conn->prepare("INSERT INTO DemandeCongeType (DemandeCongeId, TypeCongeId, NombreJours) VALUES (?, ?, ?)");
if (!$insertType) {
    echo json_encode(["success"=>false,"message"=>"Erreur préparation DemandeCongeType: ".$conn->error]); $conn->close(); exit();
}

foreach ($data['Repartition'] as $rep) {
    $code = $rep['TypeConge'];
    $jours = (float)$rep['NombreJours'];

    switch ($code) {
        case 'CP': $name = 'Congé payé'; break;
        case 'RTT': $name = 'RTT'; break;
        case 'ABS': $name = 'Congé maladie'; break;
        default: $name = $code; break;
    }
    $s = $conn->prepare("SELECT Id FROM TypeConge WHERE Nom = ?");
    $s->bind_param("s", $name);
    $s->execute();
    $res = $s->get_result();
    if ($r = $res->fetch_assoc()) {
        $typeId = (int)$r['Id'];
        $insertType->bind_param("iid", $demandeId, $typeId, $jours); // i,i,d
        $insertType->execute();
    }
    $s->close();
}
$insertType->close();

echo json_encode(["success"=>true,"message"=>"Demande soumise", "request_id"=>$demandeId]);
$conn->close();
?>
