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

// 1. Cek parameter picking_no
if(!isset($_GET['picking_no'])) {
    die("Error: Tidak ada picking list yang dipilih");
}

// 2. Ambil dan bersihkan data picking_no
$picking_nos = is_array($_GET['picking_no']) ? $_GET['picking_no'] : [$_GET['picking_no']];
$clean_picking_nos = array_map([$db, 'escape'], $picking_nos);
$picking_list = "'" . implode("','", $clean_picking_nos) . "'";

// 3. Query untuk mendapatkan total material dan remark
$sql = "SELECT 
          m.component as part_number,
          p.name as part_name,
          p.uom,
          SUM(m.quantity_needed) as total_qty,
          GROUP_CONCAT(DISTINCT m.picking_no ORDER BY m.picking_no SEPARATOR ', ') as picking_sources
        FROM material_forecasts m
        JOIN products p ON m.component = p.part_number
        WHERE m.picking_no IN ($picking_list)
        GROUP BY m.component
        ORDER BY p.name";

$result = $db->query($sql);

if(!$result) {
    die("Error query database: " . $db->get_last_error());
}

// 4. Hitung total item
$total_items = $db->num_rows($result);

// 5. Collect data for both HTML and potential Excel export
$items = [];
$picking_sources = [];
if($total_items > 0) {
    while($row = $db->fetch_assoc($result)) {
        $items[] = $row;
        $picking_sources = array_merge($picking_sources, explode(', ', $row['picking_sources']));
    }
}
$unique_picking_sources = array_unique($picking_sources);

// Handle Excel Export
if(isset($_GET['export']) && $_GET['export'] == 'excel') {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=Summary_Picking_List_".date('Ymd').".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    echo "<table border='1'>";
    echo "<tr>
        <th>No</th>
        <th>Part Number</th>
        <th>Nama Material</th>
        <th>Satuan</th>
        <th>Total Qty</th>
    </tr>";
    
    if($total_items > 0) {
        $i = 1;
        foreach($items as $row) {
            echo "<tr>
                <td>".$i++."</td>
                <td>".$row['part_number']."</td>
                <td>".$row['part_name']."</td>
                <td>".$row['uom']."</td>
                <td>".number_format($row['total_qty'], 2)."</td>
            </tr>";
        }
    } else {
        echo "<tr><td colspan='5'>Tidak ada data material</td></tr>";
    }
    
    echo "</table>";
    
    // Add notes section
    echo "<br><br><strong>Picking List yang Dipilih:</strong><br>";
    foreach($unique_picking_sources as $source) {
        echo "- ".$source."<br>";
    }
    
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Summary Picking List</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .btn { 
            display: inline-block;
            padding: 6px 12px;
            margin: 5px;
            background: #337ab7;
            color: white;
            text-decoration: none;
            border-radius: 4px;
        }
        .btn:hover { background: #286090; }
        .notes {
            margin-top: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .btn-excel {
            background: #1d6f42;
        }
        .btn-excel:hover {
            background: #165a35;
        }
    </style>
</head>
<body>
    <h2>Summary Material</h2>
    
    <!-- Informasi Picking List -->
    <div style="margin-bottom: 20px;">
        <p><strong>Total Material:</strong> <?php echo $total_items; ?> jenis</p>
    </div>
    
    <!-- Tabel Material -->
    <table>
        <thead>
            <tr>
                <th width="5%">No</th>
                <th width="20%">Part Number</th>
                <th width="35%">Nama Material</th>
                <th width="15%">Satuan</th>
                <th width="25%" class="text-right">Total Qty</th>
            </tr>
        </thead>
        <tbody>
            <?php if($total_items > 0): ?>
                <?php $i = 1; ?>
                <?php foreach($items as $row): ?>
                <tr>
                    <td class="text-center"><?php echo $i++; ?></td>
                    <td><?php echo $row['part_number']; ?></td>
                    <td><?php echo $row['part_name']; ?></td>
                    <td class="text-center"><?php echo $row['uom']; ?></td>
                    <td class="text-right"><?php echo number_format($row['total_qty'], 2); ?></td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="5" class="text-center">Tidak ada data material</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
    
    <!-- Catatan Picking List -->
    <div class="notes">
        <h3>Catatan:</h3>
        <p><strong>Picking List yang Dipilih:</strong></p>
        <ul>
            <?php foreach($unique_picking_sources as $source): ?>
                <li><?php echo $source; ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    
    <!-- Tombol Aksi -->
    <div style="margin-top: 20px;">
        <a href="picking_list.php" class="btn">Kembali ke Daftar</a>
        <a href="print_summary_picking.php?picking_no=<?php echo implode('&picking_no[]=', $clean_picking_nos); ?>" 
           target="_blank" class="btn">Cetak Summary</a>
        <a href="view_summary_picking.php?<?php 
            echo http_build_query(array('picking_no' => $_GET['picking_no'])); 
            ?>&export=excel" class="btn btn-excel">Export ke Excel</a>
    </div>
</body>
</html>