<?php
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['numeroUtilise'], $_POST['libelle'], $_POST['typeUtilisation'])) {
        $numeroUtilise = $_POST['numeroUtilise'];
        $libelle = $_POST['libelle'];
        $dateUtilisation = date('Y-m-d H:i:s');
        $typeUtilisation = $_POST['typeUtilisation'];

        switch ($typeUtilisation) {
            case 'bordereau':
                $stmt = $pdo->prepare("UPDATE bordereaux SET utilise = TRUE, date_utilisation = :date_utilisation, libelle = :libelle WHERE numero = :numero");
                break;
            case 'proforma':
                $stmt = $pdo->prepare("UPDATE proformas SET utilise = TRUE, date_utilisation = :date_utilisation, libelle = :libelle WHERE numero = :numero");
                break;
            case 'facture':
                $stmt = $pdo->prepare("UPDATE factures SET utilise = TRUE, date_utilisation = :date_utilisation, libelle = :libelle WHERE numero = :numero");
                break;
            default:
                die("Type d'utilisation invalide.");
        }

        $stmt->execute(['numero' => $numeroUtilise, 'date_utilisation' => $dateUtilisation, 'libelle' => $libelle]);
        header("Location: index.php");
        exit();
    }
}

// Pagination pour bordereaux
$pageBordereaux = isset($_GET['page_bordereaux']) ? (int)$_GET['page_bordereaux'] : 1;
$limit = 10;
$offsetBordereaux = ($pageBordereaux - 1) * $limit;

$stmtCountBordereaux = $pdo->query("SELECT COUNT(*) FROM bordereaux WHERE utilise = FALSE");
$totalRecordsBordereaux = $stmtCountBordereaux->fetchColumn();
$totalPagesBordereaux = ceil($totalRecordsBordereaux / $limit);

$stmtBordereaux = $pdo->prepare("SELECT * FROM bordereaux WHERE utilise = FALSE ORDER BY id LIMIT :limit OFFSET :offset");
$stmtBordereaux->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmtBordereaux->bindParam(':offset', $offsetBordereaux, PDO::PARAM_INT);
$stmtBordereaux->execute();
$bordereaux = $stmtBordereaux->fetchAll(PDO::FETCH_ASSOC);

// Pagination pour proformas
$pageProformas = isset($_GET['page_proformas']) ? (int)$_GET['page_proformas'] : 1;
$offsetProformas = ($pageProformas - 1) * $limit;

$stmtCountProformas = $pdo->query("SELECT COUNT(*) FROM proformas WHERE utilise = FALSE");
$totalRecordsProformas = $stmtCountProformas->fetchColumn();
$totalPagesProformas = ceil($totalRecordsProformas / $limit);

$stmtProformas = $pdo->prepare("SELECT * FROM proformas WHERE utilise = FALSE ORDER BY id LIMIT :limit OFFSET :offset");
$stmtProformas->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmtProformas->bindParam(':offset', $offsetProformas, PDO::PARAM_INT);
$stmtProformas->execute();
$proformas = $stmtProformas->fetchAll(PDO::FETCH_ASSOC);

// Pagination pour factures
$pageFactures = isset($_GET['page_factures']) ? (int)$_GET['page_factures'] : 1;
$offsetFactures = ($pageFactures - 1) * $limit;

$stmtCountFactures = $pdo->query("SELECT COUNT(*) FROM factures WHERE utilise = FALSE");
$totalRecordsFactures = $stmtCountFactures->fetchColumn();
$totalPagesFactures = ceil($totalRecordsFactures / $limit);

$stmtFactures = $pdo->prepare("SELECT * FROM factures WHERE utilise = FALSE ORDER BY id LIMIT :limit OFFSET :offset");
$stmtFactures->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmtFactures->bindParam(':offset', $offsetFactures, PDO::PARAM_INT);
$stmtFactures->execute();
$factures = $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>Gestion des numéros de bordereaux, proformas et factures</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>
    <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>
</head>
<body>
    <div class="container mt-5">
        <h1 class="mb-4">Gestion des numéros de bordereaux, proformas et factures</h1>
        <div class="d-flex">
            <a href="generate.php" class="btn btn-primary">Générer N° bordereau</a>
            <a href="generate_proforma.php" class="btn btn-info ml-2">Générer N° proforma</a>
            <a href="generate_facture.php" class="btn btn-warning ml-2">Générer N° facture</a>
            <a href="historique.php" class="btn btn-secondary ml-2">Historique</a>
        </div>

        <!-- Section Bordereaux -->
        <h2 class="mb-3 mt-5">Numéros de bordereaux disponibles</h2>
        <div class="card mb-4">
            <div class="card-body">
                <ul class="list-group">
                    <?php if (empty($bordereaux)): ?>
                        <li class="list-group-item">Aucun numéro de bordereau disponible.</li>
                    <?php else: ?>
                        <?php foreach ($bordereaux as $bordereau): ?>
                            <li class="list-group-item">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span><?php echo $bordereau['numero']; ?></span>
                                    <button type="button" class="btn btn-success" onclick="ouvrirModale('<?php echo $bordereau['numero']; ?>', 'bordereau')">Utiliser</button>
                                </div>
                            </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; ?>" 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; ?>"><?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; ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>

        <!-- Section Proformas -->
        <h2 class="mb-3 mt-5">Numéros de proformas disponibles</h2>
        <div class="card mb-4">
            <div class="card-body">
                <ul class="list-group">
                    <?php if (empty($proformas)): ?>
                        <li class="list-group-item">Aucun numéro de proforma disponible.</li>
                    <?php else: ?>
                        <?php foreach ($proformas as $proforma): ?>
                            <li class="list-group-item">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span><?php echo $proforma['numero']; ?></span>
                                    <button type="button" class="btn btn-success" onclick="ouvrirModale('<?php echo $proforma['numero']; ?>', 'proforma')">Utiliser</button>
                                </div>
                            </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; ?>" 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; ?>"><?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; ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>

        <!-- Section Factures -->
        <h2 class="mb-3 mt-5">Numéros de factures disponibles</h2>
        <div class="card mb-4">
            <div class="card-body">
                <ul class="list-group">
                    <?php if (empty($factures)): ?>
                        <li class="list-group-item">Aucun numéro de facture disponible.</li>
                    <?php else: ?>
                        <?php foreach ($factures as $facture): ?>
                            <li class="list-group-item">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span><?php echo $facture['numero']; ?></span>
                                    <button type="button" class="btn btn-success" onclick="ouvrirModale('<?php echo $facture['numero']; ?>', 'facture')">Utiliser</button>
                                </div>
                            </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; ?>" 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; ?>"><?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; ?>" 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>
</body>
</html>