<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');
require_once("../config/config.php");

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

$model_no   = trim($_GET['model_no'] ?? '');
$project_id = (int)($_GET['project_id'] ?? 0);

if (!$model_no || !$project_id) {
    echo json_encode([]);
    exit;
}

// ✅ STEP 1: Get item_id from inventory_master
$stmt1 = $conn->prepare("
    SELECT id 
    FROM inventory_master 
    WHERE model_no = ?
    LIMIT 1
");

$stmt1->bind_param("s", $model_no);
$stmt1->execute();
$res1 = $stmt1->get_result();

if ($res1->num_rows === 0) {
    echo json_encode([]); // ❌ model not found
    exit;
}

$item = $res1->fetch_assoc();
$item_id = $item['id'];

$stmt1->close();

// ✅ STEP 2: Get serials using item_id
$stmt2 = $conn->prepare("
    SELECT serial_no 
    FROM project_inventory_serials
    WHERE item_id = ?
    AND project_id = ?
    AND status = 'IN'
");

$stmt2->bind_param("ii", $item_id, $project_id);
$stmt2->execute();

$result = $stmt2->get_result();

$data = [];

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

echo json_encode($data);

$stmt2->close();
$conn->close();
?>