<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("../db/cn.php");
ob_start();
$conn = $connection;
// Check session
if (isset($_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['outlet_name'], $_SESSION['outlet_address'])) {
    $userName       = $_SESSION['user_name'];
    $userRole       = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name    = $_SESSION['outlet_name'];
} else {
    echo "Session variables not set. Please log in.";
    exit;
}

// --------------------- INSERT PACKING ---------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_pack'])) {
    $package_name = trim($_POST['package_name']);
    if (!empty($package_name)) {
        $date_time = date('Y-m-d H:i:s');
        $stmt = $conn->prepare("INSERT INTO `add_pack` (`package_name`, `date_time`, `user_name`) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $package_name, $date_time, $userName);
        if ($stmt->execute()) {
            // Success – reload to avoid resubmission
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $error_msg = "Error inserting record: " . $stmt->error;
        }
        $stmt->close();
    } else {
        $error_msg = "Package name cannot be empty.";
    }
}

// --------------------- DELETE PACKING ---------------------
if (isset($_GET['delete_id']) && is_numeric($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM `add_pack` WHERE `id` = ?");
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $error_msg = "Error deleting record: " . $stmt->error;
    }
    $stmt->close();
}

// --------------------- FETCH ALL RECORDS -------------------
$result = $conn->query("SELECT * FROM `add_pack` ORDER BY `id` DESC");

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Add GatePass</title>

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<style>
    body {
        font-family: 'Quicksand', sans-serif;
    }

    .chart-container {
        position: relative;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 10px;
        padding: 15px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
        max-width: 100%;
        height: auto;
    }

    .bg-gradient-primary {
        background: #0A4657;
        color: #fff;
    }

    .btn-primary {
        background: #0A4657;
        color: #fff;
        border: 1px #0A4657 solid;
    }

    .btn-primary:hover {
        background: #fff;
        border: 1px #0A4657 solid;
        color: #0A4657;
    }

    .chart-container {
        position: relative;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 10px;
        padding: 15px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
        max-width: 100%;
        height: auto;
    }

    .fa-download:hover {
        color: #953E39;
    }

    .form-control,
    option {
        font-weight: 700;
        color: #000;
    }
</style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php include("common/sd.php"); ?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>
                    <!-- Topbar Navbar -->
                    <?php include('common/log.php'); ?>
                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-sm-9">
                            <h3 style="color:#212529; font-weight:700;">Add Packing</h3>
                        </div>
                        <div class="col-sm-3"></div>
                    </div>
                    <br />

                    <!-- Error Message -->
                    <?php if (isset($error_msg)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?= htmlspecialchars($error_msg) ?>
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Form Column -->
                        <div class="col-sm-4">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3 bg-gradient-primary">
                                    <h6 class="m-0 font-weight-bold text-white">Add New Package</h6>
                                </div>
                                <div class="card-body">
                                    <form method="post" action="">
                                        <div class="form-group">
                                            <label for="package_name">Package Name <span class="text-danger">*</span></label>
                                            <input type="text" name="package_name" id="package_name"
                                                   class="form-control" placeholder="Enter package name" required>
                                        </div>
                                        <button type="submit" name="add_pack" class="btn btn-primary btn-block">
                                            <i class="fas fa-plus-circle"></i> Add Packing
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Table Column -->
                        <div class="col-sm-8">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3 bg-gradient-primary">
                                    <h6 class="m-0 font-weight-bold text-white">Packing List</h6>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover text-center" id="dataTable" width="100%" cellspacing="0">
                                            <thead class="thead-light">
                                                <tr>
                                                    <th>ID</th>
                                                    <th>Package Name</th>
                                                    <th>Date Time</th>
                                                    <th>User Name</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while ($row = $result->fetch_assoc()): ?>
                                                        <tr class="font-weight-bold text-capitalize">
                                                            <td><?= htmlspecialchars($row['id']) ?></td>
                                                            <td><?= htmlspecialchars($row['package_name']) ?></td>
                                                            <td><?= htmlspecialchars($row['date_time']) ?></td>
                                                            <td><?= htmlspecialchars($row['user_name']) ?></td>
                                                            <td>
                                                                <button class="btn btn-danger btn-sm delete-btn"
                                                                        data-id="<?= $row['id'] ?>"
                                                                        data-name="<?= htmlspecialchars($row['package_name']) ?>">
                                                                    <i class="fas fa-trash-alt"></i> 
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center">No records found.</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php"); ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
         aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

    <!-- SweetAlert2 Delete Confirmation -->
    <script>
        $(document).ready(function() {
            $('.delete-btn').on('click', function() {
                var id = $(this).data('id');
                var name = $(this).data('name');
                Swal.fire({
                    title: 'Are you sure?',
                    text: "You want to delete package \"" + name + "\"?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Redirect to delete with ID
                        window.location.href = '?delete_id=' + id;
                    }
                });
            });
        });
    </script>


    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>