<?php
// POS Principal
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . "/../../config/db.php";
require_once __DIR__ . "/pos_guard.php"; // inclure en premier après db et session

if (!isset($_SESSION['user']['id'])) {
    header("Location: /eagle_client_istanbulcups/index.php?page=login");
    exit;
}

$utilisateur_id = $_SESSION['user']['id'];
$session_id = (int)($_SESSION['session_caisse_id'] ?? 0);
$caisse_id = (int)($_SESSION['pos_caisse_id'] ?? 0);

if (!$session_id || !$caisse_id) {
    header("Location: /eagle_client_istanbulcups/index.php?page=pos-select-caisse");
    exit;
}

/* =======================
   SESSION DE CAISSE ACTIVE
======================= */
$stmt = $conn->prepare("SELECT * FROM sessions_caisse WHERE id=? LIMIT 1");
$stmt->execute([$session_id]);
$session_caisse = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$session_caisse) {
    header("Location: /eagle_client_istanbulcups/index.php?page=pos-select-caisse");
    exit;
}

$soldeOuverture = (float)$session_caisse['solde_ouverture'];

/* =======================
   TICKETS POS POUR IMPRESSION
======================= */

    $printJob = $conn->prepare("
    SELECT id, vente_id
    FROM print_jobs
    WHERE statut='pending'
      AND session_caisse_id = ?
    AND utilisateur_id = ?
    ORDER BY id ASC
    LIMIT 1
");
$printJob->execute([$session_id,$utilisateur_id]);
$job = $printJob->fetch(PDO::FETCH_ASSOC);



/* =======================
   SOLDE JOURNALIER
======================= */
$stmt = $conn->prepare("
    SELECT
        COALESCE(SUM(CASE WHEN type_operation='entree' THEN montant END),0) AS total_entrees,
        COALESCE(SUM(CASE WHEN type_operation='sortie' THEN montant END),0) AS total_sorties
    FROM operations_caisse
    WHERE session_caisse_id = ?
");
$stmt->execute([$session_id]);
$totaux = $stmt->fetch(PDO::FETCH_ASSOC);
$soldeJournalier = $totaux['total_entrees'] - $totaux['total_sorties'];

/* =======================
   DONNÉES POS
======================= */
$produits = $conn->query("
    SELECT p.id, p.nom, p.prix_vente, p.categorie_id, p.image,
           COALESCE(SUM(sd.quantite),0) AS quantite
    FROM produits p
    LEFT JOIN stock_depot sd ON sd.produit_id = p.id
    GROUP BY p.id
    HAVING quantite > 0
    ORDER BY p.nom
")->fetchAll(PDO::FETCH_ASSOC);

$categories = $conn->query("SELECT id, nom FROM categories ORDER BY nom")->fetchAll(PDO::FETCH_ASSOC);
$clients = $conn->query("SELECT idClient, nom FROM clients WHERE statut='Actif' ORDER BY nom")->fetchAll(PDO::FETCH_ASSOC);
$modepaiement = $conn->query("SELECT id, libelle FROM modes_paiement ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);

$modepaiementOptionsHtml = '';
foreach ($modepaiement as $m) {
    $modepaiementOptionsHtml .= '<option value="'.$m['id'].'">'.htmlspecialchars($m['libelle']).'</option>';
}

/* ID Client POS */
$clientPosId = null;
foreach ($clients as $c) {
    if ($c['nom'] === 'Client POS') {
        $clientPosId = $c['idClient'];
        break;
    }
}


?>
<style>
:root {
    --pos-orange: #f57c00;
    --pos-orange-dark: #ef6c00;
    --pos-orange-light: #fff3e0;
}

.pos-page .bg-danger { background-color: var(--pos-orange) !important; }
.pos-page .btn-danger { background-color: var(--pos-orange) !important; border-color: var(--pos-orange) !important; }
.pos-page .btn-danger:hover { background-color: var(--pos-orange-dark) !important; border-color: var(--pos-orange-dark) !important; }
.pos-page .btn-outline-danger { color: var(--pos-orange) !important; border-color: var(--pos-orange) !important; }
.pos-page .btn-outline-danger:hover, .pos-page .btn-outline-danger.active { background-color: var(--pos-orange) !important; color: #fff !important; }
.pos-page .text-danger { color: var(--pos-orange) !important; }

.paiement-card { cursor: pointer; padding: 15px; border: 2px solid #eee; transition: 0.2s; }
.paiement-card:hover { border-color: var(--pos-orange); }
.paiement-card.active { border-color: var(--pos-orange); background: var(--pos-orange-light); }
</style>

<div class="container-fluid pos-page">
    <h1 class="mt-4">Ventes</h1>

    <div class="alert alert-info d-flex justify-content-between">
        <div>
            <strong>Session #<?= $session_id ?></strong><br>
            Solde d’ouverture : <strong><?= number_format($soldeOuverture,2,',',' ') ?> FCFA</strong><br>
            Solde journalier : <strong><?= number_format($soldeJournalier,2,',',' ') ?> FCFA</strong>
        </div>
        <div>
            <a href="/eagle_client_istanbulcups/index.php?page=fermer_caisse"
               class="btn btn-outline-danger btn-sm"
               onclick="return confirm('Clôturer la caisse ?')">Fermer caisse</a>
        </div>
    </div>

    <div class="row">
        <!-- PRODUITS -->
        <div class="col-md-8">
            <input id="searchProduit" class="form-control mb-3" placeholder="Rechercher un produit">
            <div class="mb-3 d-flex flex-wrap gap-2">
                <button class="btn btn-outline-dark btn-sm active" onclick="filterCategorie('all', this)">Tous</button>
                <?php foreach ($categories as $c): ?>
                    <button class="btn btn-outline-danger btn-sm"
                            onclick="filterCategorie(<?= $c['id'] ?>, this)">
                        <?= htmlspecialchars($c['nom'], ENT_QUOTES,'UTF-8') ?>
                    </button>
                <?php endforeach; ?>
            </div>

            <div class="row" id="produitsGrid">
                <?php foreach ($produits as $p): ?>
                    <div class="col-md-3 mb-3 produit-card" data-categorie="<?= (int)$p['categorie_id'] ?>">
                        <div class="card h-100 shadow-sm">
                            <?php if (!empty($p['image'])): ?>
                                <img src="/eagle_client_istanbulcups/public/uploads/produits/<?= htmlspecialchars($p['image']) ?>"
                                     alt="<?= htmlspecialchars($p['nom']) ?>"
                                     class="card-img-top" style="height:120px; object-fit:cover;">
                            <?php else: ?>
                                <div class="text-center py-4 bg-light"><small class="text-muted">Aucune image</small></div>
                            <?php endif; ?>
                            <div class="card-body text-center">
                                <h6><?= htmlspecialchars($p['nom']) ?></h6>
                                <small class="text-muted d-block">Stock : <?= (int)$p['quantite'] ?></small>
                                <strong><?= number_format($p['prix_vente'],0,'',' ') ?> FCFA</strong>
                               <button type="button"
                                        class="btn btn-danger btn-sm w-100 mt-2"
                                        onclick='addToCart(<?= json_encode($p, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)'>
                                    Ajouter
                              </button>

                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- PANIER -->
        <div class="col-md-4">
            <div class="card shadow position-sticky" style="top:80px;">
                <div class="card-header bg-danger text-white">Panier</div>
                <div class="card-body">

                    <label class="fw-bold mb-1">Client</label>
                    <select id="clientSelect" class="form-select mb-2">
                        <?php foreach ($clients as $c): ?>
                            <option value="<?= (int)$c['idClient'] ?>" <?= $c['idClient']==$clientPosId?'selected':'' ?>>
                                <?= htmlspecialchars($c['nom']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <div id="cartItems"></div>
                    <hr>

                    <input id="remise" type="number" class="form-control mb-2" placeholder="Remise (FCFA)" value="0">
                    <input id="montantVerse" type="number" class="form-control mb-2" placeholder="Montant versé">

                    <h5>Total : <strong><span id="totalPanier">0</span></strong> FCFA</h5>
                    <h6 class="text-success">Monnaie : <span id="monnaie">0</span> FCFA</h6>

                    <div class="col-md-12">
                        <label>Mode Paiement</label>
                        <select id="modePaiement" class="form-control"><?= $modepaiementOptionsHtml ?></select>
                    </div>

                    <button class="btn btn-primary w-100 mt-3" onclick="savePosVente()">PAYER</button>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if ($job): ?>
<input type="hidden"
       id="printJob"
       data-job-id="<?= (int)$job['id'] ?>"
       data-vente-id="<?= (int)$job['vente_id'] ?>">
<?php endif; ?>

<?php include __DIR__ . '/../../includes/layout_end.php'; ?>

<script>
let currentCategorie = 'all';

function filterCategorie(categorieId, btn) {
    currentCategorie = categorieId;

    // gestion bouton actif
    document.querySelectorAll('.pos-page .btn-outline-danger, .pos-page .btn-outline-dark')
        .forEach(b => b.classList.remove('active'));
    btn.classList.add('active');

    applyFilters();
}

function applyFilters() {
    const search = document.getElementById('searchProduit').value.toLowerCase();
    const produits = document.querySelectorAll('.produit-card');

    produits.forEach(card => {
        const cat = card.getAttribute('data-categorie');
        const nom = card.innerText.toLowerCase();

        const matchCategorie =
            currentCategorie === 'all' || cat === String(currentCategorie);

        const matchSearch = nom.includes(search);

        card.style.display = (matchCategorie && matchSearch) ? '' : 'none';
    });
}
</script>
<script>
document.getElementById('searchProduit').addEventListener('keyup', applyFilters);
</script>



<script src="/eagle_client_istanbulcups/public/js/pos.js"></script>


<script>
function savePosVente() {
    if (cart.length === 0) {
        alert('Panier vide');
        return;
    }

    // Créer un formulaire temporaire
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '/eagle_client_istanbulcups/pages/pos/ajax/save_pos_vente.php';

    // Client
    const clientInput = document.createElement('input');
    clientInput.type = 'hidden';
    clientInput.name = 'client_id';
    clientInput.value = document.getElementById('clientSelect').value;
    form.appendChild(clientInput);

    // Remise
    const remiseInput = document.createElement('input');
    remiseInput.type = 'hidden';
    remiseInput.name = 'remise';
    remiseInput.value = document.getElementById('remise').value || 0;
    form.appendChild(remiseInput);

    // Montant versé
    const verseInput = document.createElement('input');
    verseInput.type = 'hidden';
    verseInput.name = 'montant_verse';
    verseInput.value = document.getElementById('montantVerse').value || 0;
    form.appendChild(verseInput);

    // Mode paiement
    const modeInput = document.createElement('input');
    modeInput.type = 'hidden';
    modeInput.name = 'mode_paiement_id';
    modeInput.value = document.getElementById('modePaiement').value;
    form.appendChild(modeInput);

    // Produits : envoyer en tableau classique
    cart.forEach((p, i) => {
        const idInput = document.createElement('input');
        idInput.type = 'hidden';
        idInput.name = `produits[${i}][id]`;
        idInput.value = p.id;
        form.appendChild(idInput);

        const qteInput = document.createElement('input');
        qteInput.type = 'hidden';
        qteInput.name = `produits[${i}][quantite]`;
        qteInput.value = p.qte;
        form.appendChild(qteInput);
    });

    document.body.appendChild(form);
    form.submit();
}
</script>
