<?php
require_once __DIR__ . "/../../config/db.php";

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

if (!$id) {
    echo json_encode(['success' => false, 'message' => 'ID invalide']);
    exit;
}

$conn->beginTransaction();

try {

    //  récupérer devis
    $stmt = $conn->prepare("SELECT * FROM devis WHERE id=?");
    $stmt->execute([$id]);
    $devis = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$devis) {
        throw new Exception("Devis introuvable");
    }

    if ($devis['statut'] !== 'valide') {
        throw new Exception("Devis non valide");
    }

    /* ===============================
       NUMÉRO AUTO
    ================================= */
    $stmt = $conn->prepare("
        SELECT COUNT(*) 
        FROM devis 
        WHERE YEAR(date_devis)=YEAR(NOW()) 
        AND MONTH(date_devis)=MONTH(NOW())
    ");
    $stmt->execute();
    $nb = $stmt->fetchColumn();

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


    //  créer commande
    $stmt = $conn->prepare("
        INSERT INTO commandes_clients
        (numero, devis_id, client_id, date_commande, total_ht, taxe, remise, total_ttc, statut, utilisateur_id, created_at)
        VALUES (?,?,?,?,?,?,?,?,?,?,NOW())
    ");

    $stmt->execute([
        $numero,
        $devis['id'],
        $devis['client_id'],
        date("Y-m-d H:i:s"),
        $devis['total_ht'],
        $devis['taxe'],
        $devis['remise'],
        $devis['total_ttc'],
        'en_cours',
        $devis['utilisateur_id']
    ]);

    $commande_id = $conn->lastInsertId();

    //  récupérer détails devis
    $details = $conn->prepare("SELECT * FROM devis_details WHERE devis_id=?");
    $details->execute([$id]);

    foreach ($details as $d) {

        $stmt = $conn->prepare("
            INSERT INTO commandes_clients_details
            (commande_id, produit_id, quantite, prix, total)
            VALUES (?,?,?,?,?)
        ");

        $stmt->execute([
            $commande_id,
            $d['produit_id'],
            $d['quantite'],
            $d['prix'],
            $d['total']
        ]);
    }

    // 🔹 mettre devis en transformé
    $conn->prepare("UPDATE devis SET statut='transforme' WHERE id=?")
         ->execute([$id]);

    $conn->commit();

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    $conn->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}