<?php
// get_dc_items.php - FIXED for 500 Error

error_reporting(E_ALL);
ini_set('display_errors', 1);   // Temporarily show errors for debugging

require_once("../config/config.php");

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Only POST allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$dc_ids = array_map('intval', $input['dc_ids'] ?? []);

if (empty($dc_ids)) {
    echo json_encode(['success' => false, 'message' => 'No Delivery Challan selected']);
    exit;
}

$placeholders = str_repeat('?,', count($dc_ids) - 1) . '?';

// ==================== MOST COMMON PROBLEM AREA ====================
// Change these table/column names according to your actual database
$sql = "
    SELECT 
        dci.item_id,dci.serial_number, dc.id AS dc_id,
        im.name,
        im.model_no,
        im.uom,
        dci.issued_qty AS dc_quantity,
        COALESCE(dci.rate, 0) AS rate
    FROM delivery_challan_items dci
    JOIN delivery_challan dc ON dc.id = dci.dc_id
    JOIN inventory_master im ON dci.item_id = im.id
    
    WHERE dci.dc_id IN ($placeholders)
    ORDER BY im.name ASC
";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    echo json_encode([
        'success' => false,
        'message' => 'SQL Prepare Failed: ' . $conn->error
    ]);
    exit;
}

$stmt->bind_param(str_repeat('i', count($dc_ids)), ...$dc_ids);
$stmt->execute();
$result = $stmt->get_result();

$items = [];
while ($row = $result->fetch_assoc()) {
    $items[] = [
        'item_id'     => (int)$row['item_id'],
        'name'        => $row['name'],
        'model_no'    => $row['model_no'] ?? '',
        'serial_number'   => $row['serial_number'] ?? '',
        'uom'         => $row['uom'] ?? 'NOS',
        'dc_quantity' => (float)$row['dc_quantity'],
        'pending_qty' => (float)$row['dc_quantity'],
        'rate'        => (float)$row['rate'],
        'dc_id'       => (int)$row['dc_id']
    ];
}

$stmt->close();
$conn->close();

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