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

// Tangkap bulan dan tahun dari parameter GET, dengan default ke bulan dan tahun saat ini
$month = isset($_GET['month']) ? intval($_GET['month']) : date('m');
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');

// Issue picking list
if (isset($_POST['issue_picking_list'])) {
    $month = isset($_POST['month']) ? intval($_POST['month']) : date('m');
    $year = isset($_POST['year']) ? intval($_POST['year']) : date('Y');
    
    // Update status to 'issued' and set issued_at timestamp
    global $db;
    $db->query("UPDATE material_forecasts SET status='issued', issued_at=NOW() 
                WHERE month={$month} AND year={$year} AND status='pending'");
    
    if ($db->affected_rows() > 0) {
        $session->msg('s', "Picking list issued successfully!");
        redirect('issue_picking_list.php?month='.$month.'&year='.$year, false);
    } else {
        $session->msg('d', "Failed to issue picking list or no pending items found.");
        redirect('issue_picking_list.php?month='.$month.'&year='.$year, false);
    }
}

// Get material forecasts data
$forecasts = find_by_sql("SELECT * FROM material_forecasts WHERE month={$month} AND year={$year} ORDER BY component");

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

<div class="row">
    <div class="col-md-12">
        <!-- Formulir untuk memilih bulan dan tahun -->
        <form action="issue_picking_list.php" method="get" class="form-inline">
            <div class="form-group">
                <label for="month">Month:</label>
                <select name="month" id="month" class="form-control">
                    <?php for ($m = 1; $m <= 12; $m++) : ?>
                        <option value="<?php echo $m; ?>" <?php echo ($month == $m) ? 'selected' : ''; ?>>
                            <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                        </option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="year">Year:</label>
                <select name="year" id="year" class="form-control">
                    <?php for ($y = date('Y') + 2; $y >= 2000; $y--) : ?>
                        <option value="<?php echo $y; ?>" <?php echo ($year == $y) ? 'selected' : ''; ?>>
                            <?php echo $y; ?>
                        </option>
                    <?php endfor; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Filter</button>
        </form>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-info">
            <div class="panel-heading">Picking List - <?php echo date('F Y', mktime(0, 0, 0, $month, 1, $year)); ?></div>
            <div class="panel-body">
                <form method="post" action="issue_picking_list.php">
                    <input type="hidden" name="month" value="<?php echo $month; ?>">
                    <input type="hidden" name="year" value="<?php echo $year; ?>">
                    
                    <?php if (!empty($forecasts)) : ?>
                        <button type="submit" name="issue_picking_list" class="btn btn-primary mb-3">Issue Picking List</button>
                        <button id="export-picking-list" class="btn btn-success mb-3">Export to Excel</button>
                        
                        <table id="picking-list-table" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Component</th>
                                    <th>New Code</th>
                                    <th>Name</th>
                                    <th>UOM</th>
                                    <th>Quantity Needed</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($forecasts as $index => $forecast) : ?>
                                    <tr>
                                        <td><?php echo $index + 1; ?></td>
                                        <td><?php echo remove_junk($forecast['component']); ?></td>
                                        <td><?php echo remove_junk($forecast['new_code']); ?></td>
                                        <td><?php echo remove_junk($forecast['name']); ?></td>
                                        <td><?php echo remove_junk($forecast['uom']); ?></td>
                                        <td><?php echo number_format($forecast['quantity'], 2); ?></td>
                                        <td>
                                            <span class="label label-<?php 
                                                echo $forecast['status'] == 'completed' ? 'success' : 
                                                     ($forecast['status'] == 'issued' ? 'warning' : 'default'); ?>">
                                                <?php echo ucfirst($forecast['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($forecast['status'] == 'issued') : ?>
                                                <a href="complete_item.php?id=<?php echo (int)$forecast['id']; ?>" 
                                                   class="btn btn-xs btn-success" title="Mark as Completed">
                                                   <i class="glyphicon glyphicon-ok"></i>
                                                </a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else : ?>
                        <div class="alert alert-info">No material forecasts found for the selected month and year.</div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
document.getElementById('export-picking-list').addEventListener('click', function () {
    let wb = XLSX.utils.table_to_book(document.getElementById('picking-list-table'), { sheet: "Picking List" });
    XLSX.writeFile(wb, 'Picking_List_<?php echo date('F_Y', mktime(0, 0, 0, $month, 1, $year)); ?>.xlsx');
});
</script>

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