<?php
// ini_set('display_errors', 1);
// error_reporting(E_ALL);

define("ADMIN", true);
require_once("../../common/lib.php");
require_once("../../common/define.php");
define("TITLE_ELEMENT", 'Liste des Mouvements de Stock');
if(!isset($_SESSION['user'])){
    header("Location: /admin/login.php");
    exit();
}

// if($_SESSION['user']['type'] == "production"){
    // header("Location: /admin/");
    // exit();
// }


require_once("../includes/fn_module.php");  

?>
<!DOCTYPE html>
<head>
    <?php include("../includes/inc_header_common.php"); ?>
 <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">

</head>
<body>
    <div id="wrapper">
        <?php include("../includes/inc_top.php"); ?>
        <div id="page-wrapper">
            <div class="page-header">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-8">
                            <h1><i class="fa fa-balance-scale"></i> Liste des Mouvements de Stock</h1>
                        </div>
                    </div>
                </div>
            </div>
            <div class="container-fluid">
                <div class="alert-container">
                    <div class="alert alert-success alert-dismissable"></div>
                    <div class="alert alert-warning alert-dismissable"></div>
                    <div class="alert alert-danger alert-dismissable"></div>
                </div>
                <div class="row" style="float:left;    width: 100%;">				




<?php


// Récupérer les mouvements de stock depuis la base de données
$query = "
SELECT 
        ms.id,
        ms.id_depot,
        ms.id_produits,
        ms.qte,
		ms.status,
        ms.type_mouvement,
        ms.source,
        ms.id_source,
        ms.date_mouvement,
        p.desingnation AS produit,
        d.name AS depot
    FROM pm_mouvement_stock ms
    LEFT JOIN pm_produitsachat p ON ms.id_produits = p.id
    LEFT JOIN pm_depot d ON ms.id_depot = d.id
    ORDER BY id DESC;
";

// Exécution de la requête
$result = @$db->query($query);

// Vérifier si des mouvements de stock ont été trouvés
if ($result !== false) {	
	
    echo "
            <h2 class='mb-4'>Liste des Mouvements de Stock</h2>
            <div class='table-responsive'>
                <table id='stockTable' class='table table-bordered table-striped'>
                    <thead class='table-dark'>
                        <tr>
                            <th>#</th>
                            <th>Dépôt</th>
                            <th>Produit</th>
                            <th>Quantité</th>
                            <th>Type de mouvement</th>
                            <th>Source</th>
                            <th>Date de création</th>
                            <th align='center'>Status</th>";
    if ($_SESSION['user']['type'] == 'administrator') {
         echo "<th>Actions</th>";
    }                            
  
  
  echo '<tr>
                    <!-- Ligne des filtres pour les colonnes -->
                    <th></th>
                    <th>
                        <select id="filterDepot" class="form-select">
                            <option value="">Tous</option>
                        </select>
                    </th>
                    <th>
                        <select id="filterProduit" class="form-select" style="width:200px">
                            <option value="">Tous</option>
                        </select>
                    </th>
                    <th></th>
                    <th>
                        <select id="filtertype" class="form-select">
                            <option value="">Tous</option>
                            <option value="ENTRÉE">Entrée</option>
                            <option value="SORTIE">Sortie</option>
                            <option value="Transfert">Transfert</option>
                        </select>
                    </th>
                    <th></th>
                    <th></th>
                    <th>
                        <select id="filterStatus" class="form-select">
                            <option value="">Tous</option>
                            <option value="Validé">Validé</option>
                            <option value="En attente">En attente</option>
                        </select>
                    </th>';
					if ($_SESSION['user']['type'] == 'administrator'){
                        echo '<th></th>';
                    }
                echo '</tr>';
                            
    echo " </tr>
	
	
                    </thead>
                    <tbody>";
    
    // Afficher chaque mouvement de stock
    while ($row = $result->fetch()) {
		
		if($row['source'] == "BE" || $row['source'] == "BR" || $row['source'] == "BF"){
			$source = $row['source']."_".$row['id_source'];
		}else{
			$source = $row['source']."_".$row['id'];
		}


		if($row['status'] == 1){
			$status = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="green" class="bi bi-check" viewBox="0 0 16 16">
<path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0m-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/>
</svg><br>Validé';

		}else if( $row['status'] == 0 && $row['id_source'] == 1 && $_SESSION['user']['id'] == 18 ){

			$status = '<a href="#" onclick="confirmAction('.$row['id'].')"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="red" class="bi bi-check" viewBox="0 0 16 16">
 <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0M5.354 4.646a.5.5 0 1 0-.708.708L7.293 8l-2.647 2.646a.5.5 0 0 0 .708.708L8 8.707l2.646 2.647a.5.5 0 0 0 .708-.708L8.707 8l2.647-2.646a.5.5 0 0 0-.708-.708L8 7.293z"/>
</svg><br>En attente</a>';			
			
		}else if( $row['status'] == 0 && $row['id_source'] == 2 && $_SESSION['user']['id'] == 19 ){

			$status = '<a href="#" onclick="confirmAction('.$row['id'].')"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="red" class="bi bi-check" viewBox="0 0 16 16">
 <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0M5.354 4.646a.5.5 0 1 0-.708.708L7.293 8l-2.647 2.646a.5.5 0 0 0 .708.708L8 8.707l2.646 2.647a.5.5 0 0 0 .708-.708L8.707 8l2.647-2.646a.5.5 0 0 0-.708-.708L8 7.293z"/>
</svg><br>En attente</a>';

		}else{
			$status = '<a href="#"  onclick="confirmAction('.$row['id'].')"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="red" class="bi bi-check" viewBox="0 0 16 16">
 <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0M5.354 4.646a.5.5 0 1 0-.708.708L7.293 8l-2.647 2.646a.5.5 0 0 0 .708.708L8 8.707l2.646 2.647a.5.5 0 0 0 .708-.708L8.707 8l2.647-2.646a.5.5 0 0 0-.708-.708L8 7.293z"/>
</svg><br>En attente</a>';
		}
		
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['depot'] . "</td>";
        echo "<td>" . $row['produit'] . "</td>";
        echo "<td>" . $row['qte'] . "</td>";
        echo "<td>" . $row['type_mouvement'] . "</td>";
        echo "<td>" . $source . "</td>";
        echo "<td>" . date('Y-m-d H:i:s', strtotime($row['date_mouvement'])) . "</td>";
        echo "<td align='center'>" . $status . "</td>";
        
 if ($_SESSION['user']['type'] == 'administrator' && $row['status'] == 0) {
    echo "<td align='center'>
            <button class='btn btn-danger btn-sm' onclick='deleteAction(" . $row['id'] . ")'>Supprimer</button>
          </td>";
}else{
    echo "<td align='center'>
            <button class='btn btn-sm' btn-light>Supprimer</button>
          </td>";
}       
        echo "</tr>";
    }

    echo "</tbody>";
    echo "</table>
            </div>
     
       ";
} else {
    echo "Aucun mouvement de stock trouvé.";
}

?>

</div>


<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
function confirmAction(beId) {
    Swal.fire({
        title: 'Êtes-vous sûr ?',
        text: "Vous allez valider ce transfert vers le dépôt usine.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#28a745', // Couleur du bouton "Confirmer"
        cancelButtonColor: '#d33', // Couleur du bouton "Annuler"
        confirmButtonText: '<i class="fa fa-sign-in"></i> Confirmer',
        cancelButtonText: 'Annuler'
    }).then((result) => {
        if (result.isConfirmed) {
            // Redirection vers l'URL avec paramètres GET
            window.location.href = `../modules/valide_transfert.php?id=${beId}`;
        }
    });
}
</script>

<script>
function deleteAction(stockId) {
    Swal.fire({
        title: 'Êtes-vous sûr ?',
        text: "Cette action supprimera définitivement ce mouvement de stock.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33', // Couleur du bouton "Confirmer"
        cancelButtonColor: '#3085d6', // Couleur du bouton "Annuler"
        confirmButtonText: 'Oui, supprimer',
        cancelButtonText: 'Annuler'
    }).then((result) => {
        if (result.isConfirmed) {
            // Redirection vers le script de suppression
            window.location.href = `delete_stock.php?id=${stockId}`;
        }
    });
}
</script>


 <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
 <script>
        $(document).ready(function () {
            // Initialiser DataTable
            var table = $('#stockTable').DataTable({
				pageLength: 20, // Nombre de lignes par page
                language: {
                    url: "https://cdn.datatables.net/plug-ins/1.13.4/i18n/fr-FR.json"
                },
                initComplete: function () {
                    var api = this.api();

                    // Ajouter les options des dépôts
                    api.column(1).data().unique().sort().each(function (d) {
                        $('#filterDepot').append('<option value="' + d + '">' + d + '</option>');
                    });

                    // Ajouter les options des produits
                    api.column(2).data().unique().sort().each(function (d) {
                        $('#filterProduit').append('<option value="' + d + '">' + d + '</option>');
                    });
                }
            });

            // Filtrage pour la colonne Dépôt
            $('#filterDepot').on('change', function () {
                table.column(1).search(this.value).draw();
            });

            // Filtrage pour la colonne Produit
            $('#filterProduit').on('change', function () {
                table.column(2).search(this.value).draw();
            });

            // Filtrage pour la colonne type de mouvement
            $('#filtertype').on('change', function () {
                table.column(4).search(this.value).draw();
            });


            // Filtrage pour la colonne Statut
            $('#filterStatus').on('change', function () {
                table.column(7).search(this.value).draw();
            });
        });

        function deleteAction(id) {
            if (confirm('Êtes-vous sûr de vouloir supprimer ce mouvement ?')) {
                window.location.href = 'delete_mouvement.php?id=' + id;
            }
        }
    </script>


				</div>
            </div>
        </div>
    </div>
</body>
</html>
<?php
$_SESSION['msg_error'] = "";
$_SESSION['msg_success'] = "";
$_SESSION['msg_notice'] = ""; ?>
