<?php

require_once "config.php";

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

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        if (isset($_GET['cNoSO'])) {
            $cNoSO = $_GET['cNoSO'];

            $query = "
                SELECT 
                    ts.*,
                    b.*
                FROM tbSODtl ts
                JOIN tbbarang b ON ts.cKodeBrg = b.ckode
                WHERE ts.cNoSO = ?
                ORDER BY ts.cNoid ASC
            ";

            $stmt = $conn->prepare($query);
            $stmt->bind_param("s", $cNoSO);
            $stmt->execute();

            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $data = [];
                while ($row = $result->fetch_assoc()) {
                    if (isset($row['nharga'])) $row['nharga'] = formatRupiah($row['nharga']);
                    if (isset($row['nStotal'])) $row['nStotal'] = formatRupiah($row['nStotal']);
                    if (isset($row['nTotal'])) $row['nTotal'] = formatRupiah($row['nTotal']);
                    $data[] = $row;
                }
                echo json_encode($data);
            } else {
                echo json_encode(['error' => 'No data found for the given cNoSO']);
            }

            $stmt->close();
        } else {
            echo json_encode(['error' => 'cNoSO is required']);
        }
        break;

    default:
        echo json_encode(['error' => 'Invalid request method']);
        break;
}

$conn->close();

function formatRupiah($amount) {
    return 'Rp ' . number_format((float)$amount, 0, ',', '.');
}

?>