<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { http_response_code(200); exit(); }
header("Content-Type: application/json");
ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(E_ALL);

$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(); }

$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : null;
if (!$userId) { echo json_encode(["success"=>false,"message"=>"user_id manquant"]); $conn->close(); exit(); }

function getLeaveYear($date=null){ $d=$date?new DateTime($date):new DateTime(); $y=(int)$d->format('Y'); return ((int)$d->format('m')<6)?$y-1:$y;}
function getRTTYear($date=null){ $d=$date?new DateTime($date):new DateTime(); return (int)$d->format('Y');}
function getWorkingDays($start,$end){ $c=new DateTime($start); $e=new DateTime($end); $days=0; while($c<=$e){ $n=(int)$c->format('N'); if($n<6) $days++; $c->modify('+1 day'); } return $days;}

// Récupérer les typeIds utiles
function getTypeId($conn,$name){ $s=$conn->prepare("SELECT Id FROM TypeConge WHERE Nom=?"); $s->bind_param("s",$name); $s->execute(); $res=$s->get_result(); $id=null; if($r=$res->fetch_assoc()) $id=(int)$r['Id']; $s->close(); return $id; }
$cpTypeId = getTypeId($conn,'Congé payé');
$rttTypeId = getTypeId($conn,'RTT');
$absTypeId = getTypeId($conn,'Congé maladie');

$leaveYear = getLeaveYear();
$rttYear = getRTTYear();
$currentDate = date('Y-m-d');

// --- Soldes initiaux (CompteurConges) restent inchangés ---
$cpSolde = 0; $rttSolde = 0; $absSolde = 0;
if ($cpTypeId !== null) {
    $q="SELECT Solde FROM CompteurConges WHERE EmployeeId=? AND TypeCongeId=? AND Annee=?";
    $s=$conn->prepare($q); $s->bind_param("iii",$userId,$cpTypeId,$leaveYear); $s->execute(); $res=$s->get_result(); if($r=$res->fetch_assoc()) $cpSolde=$r['Solde']; $s->close();
}
if ($rttTypeId !== null) {
    $q="SELECT Solde FROM CompteurConges WHERE EmployeeId=? AND TypeCongeId=? AND Annee=?";
    $s=$conn->prepare($q); $s->bind_param("iii",$userId,$rttTypeId,$rttYear); $s->execute(); $res=$s->get_result(); if($r=$res->fetch_assoc()) $rttSolde=$r['Solde']; $s->close();
}
if ($absTypeId !== null) {
    $q="SELECT Solde FROM CompteurConges WHERE EmployeeId=? AND TypeCongeId=? AND Annee=?";
    $s=$conn->prepare($q); $s->bind_param("iii",$userId,$absTypeId,$rttYear); $s->execute(); $res=$s->get_result(); if($r=$res->fetch_assoc()) $absSolde=$r['Solde']; $s->close();
}

// --- Calcul CP in process : priorité DemandeCongeType, fallback = working days on DemandeConge ---
$cpInProcess = 0;
if ($cpTypeId !== null) {
    $sql = "
      SELECT dc.Id, dc.DateDebut, dc.DateFin, dct.NombreJours
      FROM DemandeConge dc
      LEFT JOIN DemandeCongeType dct
        ON dct.DemandeCongeId = dc.Id AND dct.TypeCongeId = ?
      WHERE dc.EmployeeId = ?
        AND dc.Statut IN ('En attente','Validée')
        AND dc.DateFin >= ?
        AND (dct.NombreJours IS NOT NULL OR FIND_IN_SET(?, dc.TypeCongeId))
    ";
    $s = $conn->prepare($sql);
    $s->bind_param("iiss", $cpTypeId, $userId, $currentDate, $cpTypeId);
    $s->execute();
    $res = $s->get_result();
    while ($r = $res->fetch_assoc()) {
        if ($r['NombreJours'] !== null) {
            $cpInProcess += (float)$r['NombreJours'];
        } else {
            $cpInProcess += getWorkingDays($r['DateDebut'], $r['DateFin']);
        }
    }
    $s->close();
}

// --- Calcul RTT in process (même logique) ---
$rttInProcess = 0;
if ($rttTypeId !== null) {
    $sql = "
      SELECT dc.Id, dc.DateDebut, dc.DateFin, dct.NombreJours
      FROM DemandeConge dc
      LEFT JOIN DemandeCongeType dct
        ON dct.DemandeCongeId = dc.Id AND dct.TypeCongeId = ?
      WHERE dc.EmployeeId = ?
        AND dc.Statut IN ('En attente','Validée')
        AND dc.DateFin >= ?
        AND (dct.NombreJours IS NOT NULL OR FIND_IN_SET(?, dc.TypeCongeId))
    ";
    $s = $conn->prepare($sql);
    $s->bind_param("iiss", $rttTypeId, $userId, $currentDate, $rttTypeId);
    $s->execute();
    $res = $s->get_result();
    while ($r = $res->fetch_assoc()) {
        if ($r['NombreJours'] !== null) {
            $rttInProcess += (float)$r['NombreJours'];
        } else {
            $rttInProcess += getWorkingDays($r['DateDebut'], $r['DateFin']);
        }
    }
    $s->close();
}

// --- Calcul absenteisme (validation) : priorité DemandeCongeType, fallback = DATEDIFF+1 ---
$absenteism = 0;
if ($absTypeId !== null) {
    $sql = "
      SELECT dc.DateDebut, dc.DateFin, dct.NombreJours
      FROM DemandeConge dc
      LEFT JOIN DemandeCongeType dct
        ON dct.DemandeCongeId = dc.Id AND dct.TypeCongeId = ?
      WHERE dc.EmployeeId = ?
        AND dc.Statut = 'Validée'
        AND (dct.NombreJours IS NOT NULL OR FIND_IN_SET(?, dc.TypeCongeId))
    ";
    $s = $conn->prepare($sql);
    $s->bind_param("iii", $absTypeId, $userId, $absTypeId);
    $s->execute();
    $res = $s->get_result();
    while ($r = $res->fetch_assoc()) {
        if ($r['NombreJours'] !== null) {
            $absenteism += (float)$r['NombreJours'];
        } else {
            // fallback : DATEDIFF + 1
            $d1 = new DateTime($r['DateDebut']); $d2 = new DateTime($r['DateFin']);
            $absenteism += ($d2->diff($d1)->days + 1);
        }
    }
    $s->close();
}

$availableCPCalculated = max(0, $cpSolde - $cpInProcess);
$availableRTTCalculated = max(0, $rttSolde - $rttInProcess);

echo json_encode([
  "success" => true,
  "message" => "Compteurs récupérés avec succès.",
  "counters" => [
    "availableCP" => (int)$availableCPCalculated,
    "availableRTT" => (int)$availableRTTCalculated,
    "availableABS" => (int)$absSolde,
    "rttInProcess" => (int)$rttInProcess,
    "absenteism" => (int)$absenteism
  ],
  "debug" => [
    "cpSolde"=>$cpSolde,"cpInProcess"=>$cpInProcess,
    "rttSolde"=>$rttSolde,"rttInProcess"=>$rttInProcess,
    "absSolde"=>$absSolde,"absenteism"=>$absenteism
  ]
]);

$conn->close();
?>
