<?php

require_once "config.php";

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

function formatTanggalIndo($dateStr) {
    if (empty($dateStr)) return $dateStr;

    $ts = strtotime($dateStr);
    if ($ts === false) return $dateStr;

    $bulan = [
        1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr',
        5 => 'Mei', 6 => 'Jun', 7 => 'Jul', 8 => 'Agu',
        9 => 'Sep', 10 => 'Okt', 11 => 'Nov', 12 => 'Des'
    ];

    $d = (int)date('d', $ts);
    $m = (int)date('n', $ts);
    $y = (int)date('Y', $ts);

    return $d . ' ' . $bulan[$m] . ' ' . $y;
}

$method = $_SERVER['REQUEST_METHOD'];

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

            $query = "
                SELECT 
                    so.*,
                    t.*,
                    (SELECT COUNT(*) 
                     FROM tbSODtl ts 
                     WHERE ts.cnoso = so.cNoSO) AS jumlah
                FROM tbSO so
                JOIN tbpiutang t ON so.cNoSO = t.cnomer
                WHERE so.cKode = ?
            ";

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

            $data = [];
            while ($row = $result->fetch_assoc()) {
                if (isset($row['dtanggal'])) $row['dtanggal'] = formatTanggalIndo($row['dtanggal']);
                if (isset($row['dtglorder'])) $row['dtglorder'] = formatTanggalIndo($row['dtglorder']);
                if (isset($row['etglexpired'])) $row['etglexpired'] = formatTanggalIndo($row['etglexpired']);
                if (isset($row['UserDate'])) $row['UserDate'] = formatTanggalIndo($row['UserDate']);
                if (isset($row['dTglBtlPost'])) $row['dTglBtlPost'] = formatTanggalIndo($row['dTglBtlPost']);
                if (isset($row['dTglVoid'])) $row['dTglVoid'] = formatTanggalIndo($row['dTglVoid']);

                $data[] = $row;
            }

            if (count($data) > 0) {
                echo json_encode($data);
            } else {
                echo json_encode(['error' => 'No data found for the given cKode']);
            }

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

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

$conn->close();

?>