<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

header('Content-Type: application/json');
require_once 'config.php';

$action = $_GET['action'] ?? '';

if ($action === 'get_bidders') {
    // Récupérer les soumissionnaires qui ont déposé (Date_Depot non vide)
    try {
        $stmt = $pdo->query("SELECT ID, NomPrenom, Montant_Offre, Montant, Lot_ID, Doc_1, Doc_2, Doc_3, Doc_4, Doc_5, Doc_6, Doc_7, Doc_8, Doc_9, Telephone, Type_Garantie, Montant_Cautionnement FROM cahier_des_charges WHERE Date_Depot IS NOT NULL AND Date_Depot != '' ORDER BY NomPrenom ASC");
        $bidders = $stmt->fetchAll();
        // Ajout de la version pour vérification
        echo json_encode(['success' => true, 'version' => '2.1', 'data' => $bidders]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

} elseif ($action === 'get_rankings') {
    // Récupérer le classement pour un lot spécifique ou tous
    $lot_id = isset($_GET['lot_id']) ? (int)$_GET['lot_id'] : 0;
    
    try {
        $sql = "SELECT ID, NomPrenom, Montant_Offre, Lot_ID FROM cahier_des_charges WHERE Date_Depot IS NOT NULL AND Date_Depot != '' AND Montant_Offre > 0";
        if ($lot_id > 0) {
            $sql .= " AND Lot_ID = :lot_id";
        }
        $sql .= " ORDER BY Montant_Offre DESC";
        
        $stmt = $pdo->prepare($sql);
        if ($lot_id > 0) {
            $stmt->bindParam(':lot_id', $lot_id);
        }
        $stmt->execute();
        $rankings = $stmt->fetchAll();
        
        echo json_encode(['success' => true, 'data' => $rankings]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

} elseif ($action === 'get_stats') {
    // Récupérer le dernier lot mis à jour
    try {
        $sqlLast = "SELECT ID, Lot_ID, NomPrenom, Montant_Offre, updated_at FROM cahier_des_charges 
                           WHERE Date_Depot IS NOT NULL AND updated_at IS NOT NULL 
                           ORDER BY updated_at DESC LIMIT 1";
        $stmtLast = $pdo->query($sqlLast);
        $lastUpdated = $stmtLast->fetch(PDO::FETCH_ASSOC);
        
        // Récupérer les leaders par lot
        $leaders = [];
        foreach ($lots as $lotId => $lotInfo) {
            $sqlLeader = "SELECT NomPrenom, Montant_Offre FROM cahier_des_charges 
                         WHERE Lot_ID = :lot_id AND Date_Depot IS NOT NULL 
                         ORDER BY Montant_Offre DESC LIMIT 1";
            $stmtLeader = $pdo->prepare($sqlLeader);
            $stmtLeader->execute([':lot_id' => $lotId]);
            $leader = $stmtLeader->fetch(PDO::FETCH_ASSOC);
            
            if ($leader) {
                $leaders[] = [
                    'lot_id' => $lotId,
                    'lot_nom' => $lotInfo['nom'],
                    'leader_nom' => $leader['NomPrenom'],
                    'montant' => $leader['Montant_Offre']
                ];
            }
        }
        
        echo json_encode([
            'success' => true, 
            'last_updated' => $lastUpdated,
            'leaders' => $leaders
        ]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

} elseif ($action === 'save_offer') {
    // Enregistrement de l'offre
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        echo json_encode(['success' => false, 'message' => 'Données invalides']);
        exit;
    }

    $id = $input['soumissionnaire_id'] ?? $input['id']; // Support both
    $lot_id = $input['lot_id'];
    $montant = $input['montant'];
    $telephone = $input['telephone'] ?? null;
    $type_garantie = $input['type_garantie'] ?? null;
    $montant_cautionnement = $input['montant_cautionnement'] ?? null;
    
    // Handle documents array
    $docs = [];
    if (isset($input['documents'])) {
        // Convert input array to 1-9 index map
        $inputDocs = $input['documents']; // Array of values like "1", "2", etc.
        for ($i = 1; $i <= 9; $i++) {
            $docs[$i] = in_array((string)$i, $inputDocs) ? 1 : 0;
        }
    } elseif (isset($input['docs'])) {
        $docs = $input['docs'];
    } else {
         for ($i = 1; $i <= 9; $i++) {
            $docs[$i] = 0;
        }
    }

    try {
        $sql = "UPDATE cahier_des_charges SET 
                Lot_ID = :lot_id, 
                Montant_Offre = :montant,
                Telephone = :telephone,
                Type_Garantie = :type_garantie,
                Montant_Cautionnement = :montant_cautionnement,
                Doc_1 = :doc1, Doc_2 = :doc2, Doc_3 = :doc3, 
                Doc_4 = :doc4, Doc_5 = :doc5, Doc_6 = :doc6, 
                Doc_7 = :doc7, Doc_8 = :doc8, Doc_9 = :doc9,
                updated_at = NOW()
                WHERE ID = :id";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':lot_id' => $lot_id,
            ':montant' => $montant,
            ':telephone' => $telephone,
            ':type_garantie' => $type_garantie,
            ':montant_cautionnement' => $montant_cautionnement,
            ':doc1' => $docs[1],
            ':doc2' => $docs[2],
            ':doc3' => $docs[3],
            ':doc4' => $docs[4],
            ':doc5' => $docs[5],
            ':doc6' => $docs[6],
            ':doc7' => $docs[7],
            ':doc8' => $docs[8],
            ':doc9' => $docs[9],
            ':id' => $id
        ]);

        echo json_encode(['success' => true, 'message' => 'Offre enregistrée avec succès']);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => "Erreur SQL: " . $e->getMessage()]);
    }
}
?>
