<?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; charset=utf-8');
require_once 'config/database.php';

// Définition des lots avec leurs prix d'ouverture
$lots = [
    1 => ["nom" => "Lot 1: Local Cafeterie", "prix_ouverture" => 100000],
    2 => ["nom" => "Lot 2: Local FastFood", "prix_ouverture" => 100000],
    3 => ["nom" => "Lot 3: Local Superette", "prix_ouverture" => 70000],
    4 => ["nom" => "Lot 4: Local Kiosque Multi Service", "prix_ouverture" => 50000]
];

$action = $_GET['action'] ?? 'get_rankings';
$lot_id = isset($_GET['lot_id']) ? (int)$_GET['lot_id'] : 0;

try {
    if ($action === 'get_rankings') {
        // Récupérer le classement pour un lot spécifique ou tous
        $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(PDO::FETCH_ASSOC);
        
        // Ajouter les informations de lot et vérifier les offres invalides
        foreach ($rankings as &$ranking) {
            $lotInfo = $lots[$ranking['Lot_ID']] ?? null;
            $ranking['lot_nom'] = $lotInfo ? $lotInfo['nom'] : "Lot " . $ranking['Lot_ID'];
            $ranking['prix_ouverture'] = $lotInfo ? $lotInfo['prix_ouverture'] : 0;
            $ranking['offre_invalide'] = $ranking['Montant_Offre'] < $ranking['prix_ouverture'];
        }
        
        // Formater les lots pour l'application Android
        $lotsFormatted = [];
        foreach ($lots as $id => $lot) {
            $lotsFormatted[] = [
                $id => [
                    "nom" => $lot["nom"],
                    "prix_ouverture" => $lot["prix_ouverture"]
                ]
            ];
        }
        
        echo json_encode([
            'status' => 'OK',
            'success' => true,
            'data' => $rankings,
            'lots' => $lotsFormatted
        ]);
        
    } elseif ($action === 'get_stats') {
        // Récupérer le dernier lot mis à jour
        $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 = [];
        $lotIds = [1, 2, 3, 4];
        
        foreach ($lotIds as $lotId) {
            $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) {
                $nomLot = $lots[$lotId]['nom'] ?? "Lot " . $lotId;
                
                $leaders[] = [
                    'lot_id' => $lotId,
                    'lot_nom' => $nomLot,
                    'leader_nom' => $leader['NomPrenom'],
                    'montant' => $leader['Montant_Offre']
                ];
            }
        }
        
        echo json_encode([
            'status' => 'OK',
            'success' => true,
            'last_updated' => $lastUpdated,
            'leaders' => $leaders
        ]);
        
    } elseif ($action === 'get_bidders') {
        // Récupérer les soumissionnaires qui ont déposé
        $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 FROM cahier_des_charges WHERE Date_Depot IS NOT NULL AND Date_Depot != '' ORDER BY NomPrenom ASC");
        $bidders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'status' => 'OK',
            'success' => true,
            'version' => '2.0',
            'data' => $bidders
        ]);
        
    } else {
        echo json_encode([
            'status' => 'ERR',
            'message' => 'Action non reconnue'
        ]);
    }
    
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'ERR',
        'message' => $e->getMessage()
    ]);
}
?>