<?php
require_once 'db.php';

// Récupération des paramètres de recherche
$searchBordereaux = isset($_GET['search_bordereaux']) ? $_GET['search_bordereaux'] : '';
$searchProformas = isset($_GET['search_proformas']) ? $_GET['search_proformas'] : '';
$searchFactures = isset($_GET['search_factures']) ? $_GET['search_factures'] : '';

// Pagination pour bordereaux
$pageBordereaux = isset($_GET['page_bordereaux']) ? (int)$_GET['page_bordereaux'] : 1;
$limit = 10;
$offsetBordereaux = ($pageBordereaux - 1) * $limit;

$queryBordereaux = "SELECT * FROM bordereaux WHERE utilise = TRUE";
$paramsBordereaux = [];

if (!empty($searchBordereaux)) {
    $queryBordereaux .= " AND numero LIKE :search_bordereaux";
    $paramsBordereaux[':search_bordereaux'] = '%' . $searchBordereaux . '%';
}

$queryBordereaux .= " ORDER BY id DESC LIMIT :limit OFFSET :offset";
$paramsBordereaux[':limit'] = $limit;
$paramsBordereaux[':offset'] = $offsetBordereaux;

// Préparation de la requête pour le comptage total
$stmtCountBordereaux = $pdo->prepare("SELECT COUNT(*) FROM bordereaux WHERE utilise = TRUE" . (!empty($searchBordereaux) ? " AND numero LIKE :search_bordereaux" : ""));
$stmtCountBordereaux->execute(array_key_exists(':search_bordereaux', $paramsBordereaux) ? ['search_bordereaux' => $paramsBordereaux[':search_bordereaux']] : []);
$totalRecordsBordereaux = $stmtCountBordereaux->fetchColumn();
$totalPagesBordereaux = ceil($totalRecordsBordereaux / $limit);

// Préparation de la requête pour les bordereaux
$stmtBordereaux = $pdo->prepare($queryBordereaux);
foreach ($paramsBordereaux as $key => $value) {
    if ($key === ':limit' || $key === ':offset') {
        $stmtBordereaux->bindValue($key, $value, PDO::PARAM_INT);
    } else {
        $stmtBordereaux->bindValue($key, $value, PDO::PARAM_STR);
    }
}
$stmtBordereaux->execute();
$bordereauxUtilises = $stmtBordereaux->fetchAll(PDO::FETCH_ASSOC);

// Pagination pour proformas
$pageProformas = isset($_GET['page_proformas']) ? (int)$_GET['page_proformas'] : 1;
$offsetProformas = ($pageProformas - 1) * $limit;

$queryProformas = "SELECT * FROM proformas WHERE utilise = TRUE";
$paramsProformas = [];

if (!empty($searchProformas)) {
    $queryProformas .= " AND numero LIKE :search_proformas";
    $paramsProformas[':search_proformas'] = '%' . $searchProformas . '%';
}

$queryProformas .= " ORDER BY id DESC LIMIT :limit OFFSET :offset";
$paramsProformas[':limit'] = $limit;
$paramsProformas[':offset'] = $offsetProformas;

// Préparation de la requête pour le comptage total
$stmtCountProformas = $pdo->prepare("SELECT COUNT(*) FROM proformas WHERE utilise = TRUE" . (!empty($searchProformas) ? " AND numero LIKE :search_proformas" : ""));
$stmtCountProformas->execute(array_key_exists(':search_proformas', $paramsProformas) ? ['search_proformas' => $paramsProformas[':search_proformas']] : []);
$totalRecordsProformas = $stmtCountProformas->fetchColumn();
$totalPagesProformas = ceil($totalRecordsProformas / $limit);

// Préparation de la requête pour les proformas
$stmtProformas = $pdo->prepare($queryProformas);
foreach ($paramsProformas as $key => $value) {
    if ($key === ':limit' || $key === ':offset') {
        $stmtProformas->bindValue($key, $value, PDO::PARAM_INT);
    } else {
        $stmtProformas->bindValue($key, $value, PDO::PARAM_STR);
    }
}
$stmtProformas->execute();
$proformasUtilises = $stmtProformas->fetchAll(PDO::FETCH_ASSOC);

// Pagination pour factures
$pageFactures = isset($_GET['page_factures']) ? (int)$_GET['page_factures'] : 1;
$offsetFactures = ($pageFactures - 1) * $limit;

$queryFactures = "SELECT * FROM factures WHERE utilise = TRUE";
$paramsFactures = [];

if (!empty($searchFactures)) {
    $queryFactures .= " AND numero LIKE :search_factures";
    $paramsFactures[':search_factures'] = '%' . $searchFactures . '%';
}

$queryFactures .= " ORDER BY id DESC LIMIT :limit OFFSET :offset";
$paramsFactures[':limit'] = $limit;
$paramsFactures[':offset'] = $offsetFactures;

// Préparation de la requête pour le comptage total
$stmtCountFactures = $pdo->prepare("SELECT COUNT(*) FROM factures WHERE utilise = TRUE" . (!empty($searchFactures) ? " AND numero LIKE :search_factures" : ""));
$stmtCountFactures->execute(array_key_exists(':search_factures', $paramsFactures) ? ['search_factures' => $paramsFactures[':search_factures']] : []);
$totalRecordsFactures = $stmtCountFactures->fetchColumn();
$totalPagesFactures = ceil($totalRecordsFactures / $limit);

// Préparation de la requête pour les factures
$stmtFactures = $pdo->prepare($queryFactures);
foreach ($paramsFactures as $key => $value) {
    if ($key === ':limit' || $key === ':offset') {
        $stmtFactures->bindValue($key, $value, PDO::PARAM_INT);
    } else {
        $stmtFactures->bindValue($key, $value, PDO::PARAM_STR);
    }
}
$stmtFactures->execute();
$facturesUtilises = $stmtFactures->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Historique des numéros utilisés</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .utilise {
            color: gray;
            /* text-decoration: line-through; */
        }
        .card-body {
            padding: 1rem;
        }
        .card-title {
            margin-bottom: 0.5rem;
        }
        .card-text {
            margin-bottom: 0.5rem;
        }
        .btn-container {
            margin-top: 1rem;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1 class="mb-4">Historique des numéros utilisés</h1>
        <a href="index.php" class="btn btn-primary mb-3">Retour à la gestion des numéros</a>

        <!-- Section Bordereaux -->
        <h2 class="mb-3 mt-5">Historique des numéros de bordereaux</h2>
        <form class="mb-3" method="get" action="">
            <div class="input-group">
                <input type="text" class="form-control" name="search_bordereaux" placeholder="Rechercher un numéro de bordereau" value="<?php echo htmlspecialchars($searchBordereaux); ?>">
                <div class="input-group-append">
                    <button class="btn btn-outline-secondary" type="submit">Rechercher</button>
                </div>
            </div>
        </form>
        <div class="card mb-4">
            <div class="card-body">
                <ul class="list-group">
                    <?php if (empty($bordereauxUtilises)): ?>
                        <li class="list-group-item">Aucun numéro de bordereau trouvé.</li>
                    <?php else: ?>
                        <?php foreach ($bordereauxUtilises as $bordereau): ?>
                            <li class="list-group-item utilise">
                                <strong>Numéro :</strong> <?php echo $bordereau['numero']; ?><br>
                                <strong>Date d'utilisation :</strong> <?php echo $bordereau['date_utilisation'] ? date('d/m/Y H:i:s', strtotime($bordereau['date_utilisation'])) : 'Non disponible'; ?><br>
                                <strong>Libellé :</strong> <?php echo $bordereau['libelle'] ? htmlspecialchars($bordereau['libelle']) : 'Non disponible'; ?>
                            </li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>
            </div>
        </div>

        <!-- Pagination pour bordereaux -->
        <nav aria-label="Page navigation example" class="mt-4">
            <ul class="pagination justify-content-center">
                <?php if ($pageBordereaux > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page_bordereaux=<?php echo $pageBordereaux - 1; ?>&search_bordereaux=<?php echo urlencode($searchBordereaux); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
                <?php for ($i = 1; $i <= $totalPagesBordereaux; $i++): ?>
                    <li class="page-item <?php if ($i == $pageBordereaux) echo 'active'; ?>">
                        <a class="page-link" href="?page_bordereaux=<?php echo $i; ?>&search_bordereaux=<?php echo urlencode($searchBordereaux); ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
                <?php if ($pageBordereaux < $totalPagesBordereaux): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page_bordereaux=<?php echo $pageBordereaux + 1; ?>&search_bordereaux=<?php echo urlencode($searchBordereaux); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>

        <!-- Section Proformas -->
        <h2 class="mb-3 mt-5">Historique des numéros de proformas</h2>
        <form class="mb-3" method="get" action="">
            <div class="input-group">
                <input type="text" class="form-control" name="search_proformas" placeholder="Rechercher un numéro de proforma" value="<?php echo htmlspecialchars($searchProformas); ?>">
                <div class="input-group-append">
                    <button class="btn btn-outline-secondary" type="submit">Rechercher</button>
                </div>
            </div>
        </form>
        <div class="card mb-4">
            <div class="card-body">
                <ul class="list-group">
                    <?php if (empty($proformasUtilises)): ?>
                        <li class="list-group-item">Aucun numéro de proforma trouvé.</li>
                    <?php else: ?>
                        <?php foreach ($proformasUtilises as $proforma): ?>
                            <li class="list-group-item utilise">
                                <strong>Numéro :</strong> <?php echo $proforma['numero']; ?><br>
                                <strong>Date d'utilisation :</strong> <?php echo $proforma['date_utilisation'] ? date('d/m/Y H:i:s', strtotime($proforma['date_utilisation'])) : 'Non disponible'; ?><br>
                                <strong>Libellé :</strong> <?php echo $proforma['libelle'] ? htmlspecialchars($proforma['libelle']) : 'Non disponible'; ?>
                            </li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>
            </div>
        </div>

        <!-- Pagination pour proformas -->
        <nav aria-label="Page navigation example" class="mt-4">
            <ul class="pagination justify-content-center">
                <?php if ($pageProformas > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page_proformas=<?php echo $pageProformas - 1; ?>&search_proformas=<?php echo urlencode($searchProformas); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
                <?php for ($i = 1; $i <= $totalPagesProformas; $i++): ?>
                    <li class="page-item <?php if ($i == $pageProformas) echo 'active'; ?>">
                        <a class="page-link" href="?page_proformas=<?php echo $i; ?>&search_proformas=<?php echo urlencode($searchProformas); ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
                <?php if ($pageProformas < $totalPagesProformas): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page_proformas=<?php echo $pageProformas + 1; ?>&search_proformas=<?php echo urlencode($searchProformas); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>

        <!-- Section Factures -->
        <h2 class="mb-3 mt-5">Historique des numéros de factures</h2>
        <form class="mb-3" method="get" action="">
            <div class="input-group">
                <input type="text" class="form-control" name="search_factures" placeholder="Rechercher un numéro de facture" value="<?php echo htmlspecialchars($searchFactures); ?>">
                <div class="input-group-append">
                    <button class="btn btn-outline-secondary" type="submit">Rechercher</button>
                </div>
            </div>
        </form>
        <div class="card mb-4">
            <div class="card-body">
                <ul class="list-group">
                    <?php if (empty($facturesUtilises)): ?>
                        <li class="list-group-item">Aucun numéro de facture trouvé.</li>
                    <?php else: ?>
                        <?php foreach ($facturesUtilises as $facture): ?>
                            <li class="list-group-item utilise">
                                <strong>Numéro :</strong> <?php echo $facture['numero']; ?><br>
                                <strong>Date d'utilisation :</strong> <?php echo $facture['date_utilisation'] ? date('d/m/Y H:i:s', strtotime($facture['date_utilisation'])) : 'Non disponible'; ?><br>
                                <strong>Libellé :</strong> <?php echo $facture['libelle'] ? htmlspecialchars($facture['libelle']) : 'Non disponible'; ?>
                            </li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>
            </div>
        </div>

        <!-- Pagination pour factures -->
        <nav aria-label="Page navigation example" class="mt-4">
            <ul class="pagination justify-content-center">
                <?php if ($pageFactures > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page_factures=<?php echo $pageFactures - 1; ?>&search_factures=<?php echo urlencode($searchFactures); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
                <?php for ($i = 1; $i <= $totalPagesFactures; $i++): ?>
                    <li class="page-item <?php if ($i == $pageFactures) echo 'active'; ?>">
                        <a class="page-link" href="?page_factures=<?php echo $i; ?>&search_factures=<?php echo urlencode($searchFactures); ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
                <?php if ($pageFactures < $totalPagesFactures): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page_factures=<?php echo $pageFactures + 1; ?>&search_factures=<?php echo urlencode($searchFactures); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>
    </div>

    <!-- Modale pour la saisie du libellé -->
    <div class="modal fade" id="modaleUtilisation" tabindex="-1" role="dialog" aria-labelledby="modaleUtilisationLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modaleUtilisationLabel">Utiliser le numéro</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="formUtilisation" action="" method="post">
                        <div class="form-group">
                            <label for="libelle">Libellé</label>
                            <input type="text" class="form-control" id="libelle" name="libelle" required>
                        </div>
                        <input type="hidden" id="numeroUtilise" name="numeroUtilise">
                        <input type="hidden" id="typeUtilisation" name="typeUtilisation">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
                        <button type="button" class="btn btn-primary" onclick="confirmerUtilisation()">Valider</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script>
        function ouvrirModale(numero, type) {
            document.getElementById('numeroUtilise').value = numero;
            document.getElementById('typeUtilisation').value = type;
            $('#modaleUtilisation').modal('show');
        }

        function confirmerUtilisation() {
            const libelle = document.getElementById('libelle').value;
            if (libelle.trim() === '') {
                alert("Veuillez saisir un libellé.");
                return;
            }
            document.getElementById('formUtilisation').submit();
        }
    </script>
</body>
</html>