<?php
require_once('includes/load.php');
page_require_level(3);

// Get date range from GET parameters, default to current month
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$finish_date = isset($_GET['finish_date']) ? $_GET['finish_date'] : date('Y-m-t');

include_once('layouts/header.php');
?>

<div class="row">
    <div class="col-md-12">
        <!-- Form to select date range -->
        <form action="picking_list.php" method="get" class="form-inline">
            <div class="form-group">
                <label for="start_date">Start Date:</label>
                <input type="date" name="start_date" id="start_date" 
                       class="form-control" 
                       value="<?php echo $start_date; ?>">
            </div>
            <div class="form-group">
                <label for="finish_date">Finish Date:</label>
                <input type="date" name="finish_date" id="finish_date" 
                       class="form-control" 
                       value="<?php echo $finish_date; ?>">
            </div>
            <button type="submit" class="btn btn-primary">Filter</button>
            <button type="button" class="btn btn-default" onclick="setCurrentMonth()">This Month</button>
        </form>
    </div>
</div>

<!-- Picking List Table View -->
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <h3 class="panel-title pull-left">Picking Lists from <?php echo date('d/m/Y', strtotime($start_date)); ?> to <?php echo date('d/m/Y', strtotime($finish_date)); ?></h3>
                <div class="pull-right">
                    <button id="viewSummary" class="btn btn-success btn-xs">View Summary</button>
                    <button id="selectAll" class="btn btn-default btn-xs">Select All</button>
                    <button id="deselectAll" class="btn btn-default btn-xs">Deselect All</button>
                </div>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-striped" id="pickingTable">
                    <thead>
                        <tr>
                            <th width="3%"><input type="checkbox" id="selectAllCheckbox"></th>
                            <th>No</th>
                            <th>Picking No</th>
                            <th>Schedule Date</th>
                            <th>No of Items</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $all_pickings = $db->query("SELECT 
                                                  mf.picking_no, 
                                                  MIN(ps.delivery_date) as schedule_date,
                                                  COUNT(mf.id) as item_count,
                                                  MAX(mf.printed) as printed
                                                  FROM material_forecasts mf
                                                  JOIN production_schedule ps ON mf.no_order = ps.no_order
                                                  WHERE ps.delivery_date BETWEEN '{$start_date}' AND '{$finish_date}'
                                                  GROUP BY mf.picking_no
                                                  ORDER BY schedule_date, mf.picking_no");
                        $counter = 1;
                        while($picking = $db->fetch_assoc($all_pickings)) : ?>
                            <tr>
                                <td><input type="checkbox" class="picking-checkbox" value="<?php echo $picking['picking_no']; ?>"></td>
                                <td><?php echo $counter++; ?></td>
                                <td><?php echo $picking['picking_no']; ?></td>
                                <td><?php echo date('d/m/Y', strtotime($picking['schedule_date'])); ?></td>
                                <td><?php echo $picking['item_count']; ?></td>
                                <td><?php echo $picking['printed'] ? '<span class="label label-success">Printed</span>' : '<span class="label label-warning">Pending</span>'; ?></td>
                                <td>
                                    <a href="view_picking.php?picking_no=<?php echo $picking['picking_no']; ?>" 
                                       class="btn btn-xs btn-info">
                                        <i class="glyphicon glyphicon-eye-open"></i> View
                                    </a>
                                    <a href="print_picking.php?picking_no=<?php echo $picking['picking_no']; ?>" 
                                       class="btn btn-xs btn-success" 
                                       target="_blank">
                                        <i class="glyphicon glyphicon-print"></i> Print
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Loading Modal -->
<div class="modal fade" id="loadingModal" tabindex="-1" role="dialog" aria-labelledby="loadingModalLabel" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="loadingModalLabel">Processing...</h4>
            </div>
            <div class="modal-body text-center">
                <div class="spinner" style="font-size: 50px;">
                    <i class="glyphicon glyphicon-refresh glyphicon-spin"></i>
                </div>
                <p>Preparing documents for printing. Please wait...</p>
            </div>
        </div>
    </div>
</div>

<script>
function setCurrentMonth() {
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    
    document.getElementById('start_date').value = formatDate(firstDay);
    document.getElementById('finish_date').value = formatDate(lastDay);
}

function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

$(document).ready(function() {
    // Initialize DataTable if needed
    // $('#pickingTable').DataTable();
    
    // Select all checkbox functionality
    $('#selectAllCheckbox').change(function() {
        $('.picking-checkbox').prop('checked', $(this).prop('checked'));
    });
    
    // Select All button functionality
    $('#selectAll').click(function() {
        $('.picking-checkbox').prop('checked', true);
        $('#selectAllCheckbox').prop('checked', true);
    });
    
    // Deselect All button functionality
    $('#deselectAll').click(function() {
        $('.picking-checkbox').prop('checked', false);
        $('#selectAllCheckbox').prop('checked', false);
    });
    
    // View Summary button functionality
    $('#viewSummary').click(function() {
        const selected = [];
        $('.picking-checkbox:checked').each(function() {
            selected.push($(this).val());
        });
        
        if (selected.length === 0) {
            alert('Please select at least one picking list to view summary.');
            return;
        }
        
        // Show loading modal
        $('#loadingModal').modal('show');
        
        // Build URL for summary view
        const url = 'view_summary_picking.php?picking_no[]=' + selected.join('&picking_no[]=');
        
        // Hide loading modal after a short delay
        setTimeout(function() {
            $('#loadingModal').modal('hide');
            // Redirect to summary page
            window.location.href = url;
        }, 500);
    });
    
    // Close modal on escape key if needed
    $(document).keyup(function(e) {
        if (e.key === "Escape") {
            $('#loadingModal').modal('hide');
        }
    });
});
</script>

<?php include_once('layouts/footer.php'); ?>