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

header('Content-Type: application/json');

try {
    if (!isset($_POST['picking_nos']) || empty($_POST['picking_nos'])) {
        throw new Exception('No picking numbers provided');
    }

    $picking_nos = (array)$_POST['picking_nos'];
    
    // Validate picking numbers
    foreach ($picking_nos as $no) {
        if (!preg_match('/^[A-Z0-9_-]+$/i', $no)) {
            throw new Exception('Invalid picking number format');
        }
    }

    $db = new DB();
    $placeholders = implode(',', array_fill(0, count($picking_nos), '?'));
    
    $query = "SELECT 
                mf.component as component_code,
                p.new_code,
                p.name as component_name,
                p.uom,
                SUM(mf.quantity_needed) as total_quantity
              FROM material_forecasts mf
              LEFT JOIN products p ON mf.component = p.part_number
              WHERE mf.picking_no IN ($placeholders)
              GROUP BY mf.component, p.name, p.uom
              ORDER BY p.name";

    $result = $db->query($query, $picking_nos);
    
    if (!$result) {
        throw new Exception('Database query failed: ' . $db->error());
    }

    $data = [];
    while ($row = $db->fetch_assoc($result)) {
        $data[] = $row;
    }

    echo json_encode([
        'success' => true,
        'data' => $data,
        'count' => count($data)
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error_code' => $e->getCode()
    ]);
}
?>