<?php
//session_start();
ob_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("../db/cn.php");
$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;
}

// ---------------- AJAX: Get order items for Eye Modal ----------------
if (isset($_GET['action']) && $_GET['action'] === 'get_order_items' && isset($_GET['order_id'])) {
    ob_clean();
    $order_id = $_GET['order_id'];
    $stmt = $conn->prepare("SELECT item_name, qty, package FROM gatepass WHERE order_id = ?");
    $stmt->bind_param("s", $order_id);
    $stmt->execute();
    $result = $stmt->get_result();
    ?>
    <table class="table table-bordered table-sm">
        <thead class="thead-dark">
            <tr><th>Item Name</th><th>Qty</th><th>Package</th></tr>
        </thead>
        <tbody>
        <?php while ($row = $result->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($row['item_name']) ?></td>
                <td><?= htmlspecialchars($row['qty']) ?></td>
                <td><?= htmlspecialchars($row['package']) ?></td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
    <?php
    $stmt->close();
    exit;
}

// ---------------- DELETE ORDER ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_order_id'])) {
    $order_id = $_POST['delete_order_id'];
    $stmt = $conn->prepare("DELETE FROM gatepass WHERE order_id = ?");
    $stmt->bind_param("s", $order_id);
    $stmt->execute();
    $stmt->close();
    $_SESSION['msg'] = "Order $order_id deleted successfully.";
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// ---------------- Fetch Orders Grouped by order_id ----------------
$orders = $conn->query("SELECT order_id, customer_name, customer_phone, city, transport, total_qty, date_time, user_name 
                        FROM gatepass 
                        GROUP BY order_id 
                        ORDER BY date_time DESC");

$ajax_url = htmlspecialchars($_SERVER['PHP_SELF']);
?>
<!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">
    <title>View Gate Passes</title>

    <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">
    <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/sweetalert2@11"></script>

    <style>
        body { font-family: 'Quicksand', sans-serif; }
        .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; }
        .btn-info { background: #17a2b8; color: #fff; border: 1px #17a2b8 solid; }
        .btn-info:hover { background: #fff; border: 1px #17a2b8 solid; color: #17a2b8; }
        .btn-warning { background: #ffc107; color: #000; border: 1px #ffc107 solid; }
        .btn-warning:hover { background: #fff; border: 1px #ffc107 solid; color: #ffc107; }
        .btn-danger { background: #dc3545; color: #fff; border: 1px #dc3545 solid; }
        .btn-danger:hover { background: #fff; border: 1px #dc3545 solid; color: #dc3545; }
    </style>
</head>

<body id="page-top">
<div id="wrapper">

    <?php include("common/sd.php"); ?>

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

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

            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-9">
                        <h3 style="color:#212529; font-weight:700;">Gate Pass List</h3>
                    </div>
                </div>
                <br>

                <?php if (isset($_SESSION['msg'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?= htmlspecialchars($_SESSION['msg']) ?>
                        <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
                    </div>
                    <?php unset($_SESSION['msg']); ?>
                <?php endif; ?>

                <div class="card shadow mb-4">
                    <div class="card-header py-3 bg-gradient-primary">
                        <h6 class="m-0 font-weight-bold text-white">All Gate Passes</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover" id="dataTable" width="100%" cellspacing="0">
                                <thead class="bg-dark text-white">
                                    <tr>
                                        <th>Order ID</th>
                                        <th>Customer</th>
                                        <th>Phone</th>
                                        <th>City</th>
                                        <th>Transport</th>
                                        <th>Total Qty</th>
                                        <th>Date</th>
                                        <th>User</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($orders && $orders->num_rows > 0): ?>
                                        <?php while ($order = $orders->fetch_assoc()): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($order['order_id']) ?></td>
                                            <td><?= htmlspecialchars($order['customer_name']) ?></td>
                                            <td><?= htmlspecialchars($order['customer_phone']) ?></td>
                                            <td><?= htmlspecialchars($order['city']) ?></td>
                                            <td><?= htmlspecialchars($order['transport']) ?></td>
                                            <td><?= htmlspecialchars($order['total_qty']) ?></td>
                                            <td><?= htmlspecialchars($order['date_time']) ?></td>
                                            <td><?= htmlspecialchars($order['user_name']) ?></td>
                                            <td>
                                                <!-- Eye button -->
                                                <button class="btn btn-info btn-sm view-details" 
                                                        data-order-id="<?= htmlspecialchars($order['order_id']) ?>"
                                                        title="View Items">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                <!-- Print button -->
                                                <a href="print_gatepass.php?order_id=<?= urlencode($order['order_id']) ?>" 
                                                   target="_blank" class="btn btn-warning btn-sm" title="Print">
                                                    <i class="fas fa-print"></i>
                                                </a>
                                                <!-- Delete button -->
                                                <button class="btn btn-danger btn-sm delete-order" 
                                                        data-order-id="<?= htmlspecialchars($order['order_id']) ?>"
                                                        title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="9" class="text-center">No gate passes found.</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <br><br>
        <?php include("common/main_ft.php"); ?>
    </div>
</div>

<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-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Ready to Leave?</h5>
                <button class="close" type="button" data-dismiss="modal"><span>&times;</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>

<!-- Eye Modal for Order Items -->
<div class="modal fade" id="itemsModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Order Items (<span id="modalOrderId"></span>)</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body" id="modalBodyContent">
                Loading...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="../js/sb-admin-2.min.js"></script>

<script>
$(document).ready(function() {
    // Eye button click
    $('.view-details').click(function() {
        var orderId = $(this).data('order-id');
        $('#modalOrderId').text(orderId);
        $('#modalBodyContent').html('<div class="text-center"><i class="fas fa-spinner fa-spin fa-2x"></i></div>');
        $('#itemsModal').modal('show');

        $.ajax({
            url: '<?= $ajax_url ?>',
            data: { action: 'get_order_items', order_id: orderId },
            type: 'GET',
            success: function(response) {
                $('#modalBodyContent').html(response);
            },
            error: function() {
                $('#modalBodyContent').html('<div class="alert alert-danger">Failed to load items.</div>');
            }
        });
    });

    // Delete button click
    $('.delete-order').click(function() {
        var orderId = $(this).data('order-id');
        Swal.fire({
            title: 'Are you sure?',
            text: 'You are about to delete Order ID: ' + orderId + '. This cannot be undone!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                // Submit a hidden form for deletion
                var form = $('<form method="POST" style="display:none;">');
                form.append('<input type="hidden" name="delete_order_id" value="' + orderId + '">');
                $('body').append(form);
                form.submit();
            }
        });
    });
});
</script>


    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>
<?php
ob_end_flush();
?>