<?php
include 'db.php';
include 'auth_check.php';

if (isset($_POST['os_number'])) {
    $os_number = $conn->real_escape_string($_POST['os_number']);

    $sql = "
        SELECT 
            o.id AS outward_id,
            o.os_number,
            o.outward_date,
            o.given_to,
            o.qty,
            o.remarks,
            o.purchase_stock_id,
            p.item_name,
            p.particular_name,
            p.specification,
            p.model_number,
            p.company_name,
            p.invoice_number
        FROM outward_stock o
        LEFT JOIN purchase_stock p ON o.purchase_stock_id = p.id
        WHERE o.os_number = '$os_number'
        ORDER BY o.id DESC
        LIMIT 1
    ";

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

    if ($result && $row = $result->fetch_assoc()) {
        echo json_encode([
            "purchase_stock_id" => $row['purchase_stock_id'],
            "os_number"         => $row['os_number'],
            "outward_date"      => $row['outward_date'],
            "given_to"          => $row['given_to'],
            "qty"               => $row['qty'],
            "remarks"           => $row['remarks'],
            "item_name"         => $row['item_name'],
            "particular_name"   => $row['particular_name'],
            "specification"     => $row['specification'],
            "model_number"      => $row['model_number'],
            "company_name"      => $row['company_name'],
            "invoice_number"    => $row['invoice_number']
        ]);
    } else {
        echo json_encode(["error" => "No record found"]);
    }
}
?>
