<?php

session_start();
require_once "../../config/db.php";

$utilisateur_id = $_SESSION['user']['id'] ?? null;
if (!$utilisateur_id) {
    die("Utilisateur non authentifié");
}

$commande_id = (int)($_POST['commande_id'] ?? 0);
$factures = $_POST['factures'] ?? [];

if (!$commande_id) {
    die("Commande invalide");
}

$conn->beginTransaction();

try {

    // 1. Récup commande
    $cmd = $conn->query("
        SELECT * FROM commandes_clients WHERE id=$commande_id
    ")->fetch(PDO::FETCH_ASSOC);

    if (!$cmd) throw new Exception("Commande introuvable");

    // 2. Numéro facture
     $stmt = $conn->prepare("
        SELECT COUNT(*) 
        FROM factures_clients 
        WHERE YEAR(date_facture)=YEAR(NOW()) 
        AND MONTH(date_facture)=MONTH(NOW())
    ");
    $stmt->execute();
    $nb = $stmt->fetchColumn();

    $numero = "FAC-" . date("Y/m") . "-" . str_pad($nb + 1, 3, "0", STR_PAD_LEFT);
    //$numero = "FAC-" . date("Ymd-His");

    // 3. Créer facture
    $conn->prepare("
        INSERT INTO factures_clients
        (numero, client_id, commande_id, date_facture, total_ht, total_ttc, statut, utilisateursçid)
        VALUES (?,?,?,?,0,0,'non_payee',?)
    ")->execute([
        $numero,
        $cmd['client_id'],
        $commande_id,
        date("Y-m-d H:i:s"),
        $utilisateur_id 

    ]);

    $facture_id = $conn->lastInsertId();

    $total = 0;

    // 4. Parcourir lignes
    foreach ($factures as $detail_id => $qte) {

        $qte = (float)$qte;
        if ($qte <= 0) continue;

        $d = $conn->query("
            SELECT * FROM commandes_clients_details 
            WHERE id=$detail_id
        ")->fetch(PDO::FETCH_ASSOC);

        $reste = $d['quantite_livree'] - $d['quantite_facturee'];

        if ($qte > $reste) {
            throw new Exception("Quantité invalide");
        }

        $total_ligne = $qte * $d['prix'];

        // INSERT FACTURE DETAIL
        $conn->prepare("
            INSERT INTO factures_clients_details
            (facture_id, produit_id, quantite, prix, total)
            VALUES (?,?,?,?,?)
        ")->execute([
            $facture_id,
            $d['produit_id'],
            $qte,
            $d['prix'],
            $total_ligne
        ]);

        // UPDATE facturé
        $conn->prepare("
            UPDATE commandes_clients_details
            SET quantite_facturee = quantite_facturee + ?
            WHERE id=?
        ")->execute([$qte, $detail_id]);

        $total += $total_ligne;
    }

    // 5. Calcul prorata taxe/remise
    $taxe_cmd = (float)$cmd['taxe'];
    $remise_cmd = (float)$cmd['remise'];
    $total_cmd = (float)$cmd['total_ht'];

    $ratio = ($total_cmd > 0) ? ($total / $total_cmd) : 0;

    $taxe = $taxe_cmd * $ratio;
    $remise = $remise_cmd * $ratio;

    $total_ttc = ($total + $taxe) - $remise;

    // 6. Update facture complet
    $conn->prepare("
        UPDATE factures_clients
        SET total_ht=?,
            taxe=?,
            remise=?,
            total_ttc=?,
            reste_a_payer=?
        WHERE id=?
    ")->execute([
        $total,
        $taxe,
        $remise,
        $total_ttc,
        $total_ttc,
        $facture_id
    ]);

    // 6. Vérifier si totalement facturée
    $reste_total = $conn->query("
        SELECT SUM(quantite_livree - quantite_facturee)
        FROM commandes_clients_details
        WHERE commande_id=$commande_id
    ")->fetchColumn();

    if ($reste_total <= 0) {
        $conn->prepare("
            UPDATE commandes_clients SET statut='facturee'
            WHERE id=?
        ")->execute([$commande_id]);
    }

    $conn->commit();

    header("Location: /eagle_client_istanbulcups/index.php?page=commandes_clients");
    exit;

} catch(Exception $e) {
    $conn->rollBack();
    die("Erreur : ".$e->getMessage());
}

