<?php
/**
 * API pour la gestion des Consignes Bagages
 * Répertoire: Includes/Commercial/
 * Sécurisée avec authentification
 */

include_once __DIR__ . '/../auth_check.php';

checkRateLimit($_SERVER['REMOTE_ADDR'] ?? 'unknown');

$pdo = getDbConnection();

$auth = checkApiAuth($pdo);
if (!$auth['success']) {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method !== 'GET') {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => $auth['message']]);
        exit;
    }
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$siteFilter = $_GET['site'] ?? null;

try {
    if ($method === 'GET') {
        if ($action === 'list') {
            $query = "SELECT * FROM ConsignesBagages WHERE 1=1";
            $params = [];
            
            if ($siteFilter && $siteFilter !== 'Siège') {
                $query .= " AND Site = ?";
                $params[] = $siteFilter;
            }
            
            $query .= " ORDER BY DateDepot DESC";
            
            $stmt = $pdo->prepare($query);
            $stmt->execute($params);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            exit;
        }
        
        if ($action === 'get' && isset($_GET['id'])) {
            $id = $_GET['id'];
            $site = $_GET['site'] ?? '';
            $stmt = $pdo->prepare("SELECT * FROM ConsignesBagages WHERE ConsigneID = ? AND Site = ?");
            $stmt->execute([$id, $site]);
            $consigne = $stmt->fetch();
            echo json_encode(['success' => (bool)$consigne, 'data' => $consigne]);
            exit;
        }
        
        // Default: return list
        $query = "SELECT * FROM ConsignesBagages WHERE 1=1";
        $params = [];
        if ($siteFilter && $siteFilter !== 'Siège') {
            $query .= " AND Site = ?";
            $params[] = $siteFilter;
        }
        $query .= " ORDER BY DateDepot DESC";
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
        exit;
    }

    if (!$auth['success']) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Authentification requise']);
        exit;
    }

    $inputJson = file_get_contents('php://input');
    $input = json_decode($inputJson, true);
    $input = sanitizeInput($input);

    if ($method === 'POST') {
        if ($action === 'withdraw') {
            // Retrait de consigne
            $consigneId = $input['ConsigneID'] ?? null;
            $site = $input['Site'] ?? '';
            $modifiePar = $input['ModifiePar'] ?? $auth['user_id'];
            
            if (!$consigneId) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'ConsigneID requis']);
                exit;
            }

            $stmt = $pdo->prepare("
                UPDATE ConsignesBagages SET 
                   Etat = 'Payé', DateRetrait = ?, ModifiePar = ?, DateModif = ?
                WHERE ConsigneID = ? AND Site = ?
            ");
            
            $ok = $stmt->execute([
                date('Y-m-d H:i:s'),
                $modifiePar,
                date('Y-m-d H:i:s'),
                $consigneId,
                $site
            ]);
            
            logAction($pdo, $auth['user_id'], 'WITHDRAW_CONSIGNE', $consigneId);
            
            echo json_encode(['success' => $ok]);
            exit;
        }
        
        // Création de consigne
        $consigneId = $input['ConsigneID'] ?? null;
        
        if (!$consigneId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ConsigneID requis']);
            exit;
        }

        $stmt = $pdo->prepare("
            INSERT INTO ConsignesBagages (ConsigneID, Observation, DateDepot, NumIdentite, NomPassager, NomARPassager, PrenomPassager, PrenomARPassager,Etat, MontantTicket, NbreColis, Site, UserID, DateCreation) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $ok = $stmt->execute([
            $consigneId,
            $input['Observation'] ?? '',
            $input['DateDepot'] ?? date('Y-m-d'),
            $input['NumIdentite'] ?? '',
            $input['NomPassager'] ?? '',
            $input['NomARPassager'] ?? '',
            $input['PrenomPassager'] ?? '',
            $input['PrenomARPassager'] ?? '',
            $input['Etat'] ?? 'En Cours',
            $input['MontantTicket'] ?? 0,
            $input['NbreColis'] ?? 1,
            $input['Site'] ?? '',
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s')
        ]);
        
        logAction($pdo, $auth['user_id'], 'CREATE_CONSIGNE', $consigneId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Méthode non supportée']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur API Consignes: ' . $e->getMessage()]);
}

function logAction($pdo, $userId, $action, $target) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO Journalisation (DateJournal, TimeJournal, OperateurID, Action, Details) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            date('Y-m-d'),
            date('H:i:s'),
            $userId,
            $action,
            "API: $action sur $target"
        ]);
    } catch (Exception $e) {
        // Ne pas bloquer
    }
}
?>
