<?php
// modules/distribusi_alat/index.php
// Modul lama "Distribusi Alat" diganti menjadi "Work Order Kerusakan & Pemesanan Barang".
// Data dikirim langsung ke API web app Divisi Umum agar staf tidak perlu membuka link lain.

declare(strict_types=1);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/app.php';

checkAuth();

$user = current_user() ?: [];
$units = function_exists('getUnits') ? getUnits() : [];

$apiConfigPath = __DIR__ . '/../../config/divisi_umum_api.php';
$apiConfig = is_file($apiConfigPath) ? require $apiConfigPath : [];

function du_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function du_selected($a, $b): string
{
    return (string)$a === (string)$b ? 'selected' : '';
}

function du_api_config_value(array $config, string $key, $default = '')
{
    return $config[$key] ?? $default;
}

function du_api_request(array $config, string $action, string $method = 'GET', array $payload = []): array
{
    $baseUrl = rtrim((string)du_api_config_value($config, 'base_url', 'https://drarnya.itcprogram.com'), '/');
    $timeout = (int)du_api_config_value($config, 'timeout', 25);
    $apiKey = trim((string)du_api_config_value($config, 'api_key', ''));

    $url = $baseUrl . '/api/work-orders?action=' . rawurlencode($action);
    if ($method === 'GET' && $payload) {
        $url .= '&' . http_build_query($payload);
    }

    $headers = [
        'Accept: application/json',
        'Content-Type: application/json',
    ];
    if ($apiKey !== '') {
        $headers[] = 'X-API-Key: ' . $apiKey;
        $headers[] = 'X-Divisi-Umum-Key: ' . $apiKey;
    }

    if (!function_exists('curl_init')) {
        throw new RuntimeException('Ekstensi PHP cURL belum aktif di hosting. Aktifkan cURL agar bisa konek ke API Divisi Umum.');
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    $raw = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($errno) {
        throw new RuntimeException('Gagal menghubungi API Divisi Umum: ' . $error);
    }

    $json = json_decode((string)$raw, true);
    if (!is_array($json)) {
        throw new RuntimeException('API Divisi Umum membalas bukan JSON valid. HTTP ' . $httpCode . '. Respon: ' . substr((string)$raw, 0, 180));
    }

    if ($httpCode >= 400 || (isset($json['success']) && $json['success'] === false)) {
        throw new RuntimeException((string)($json['message'] ?? $json['error'] ?? ('API Divisi Umum error HTTP ' . $httpCode)));
    }

    return $json;
}

function du_clean_priority(string $value): string
{
    return in_array($value, ['rendah', 'normal', 'tinggi', 'urgent'], true) ? $value : 'normal';
}

function du_clean_jenis_order(string $value): string
{
    return $value === 'order_penggantian' ? 'order_penggantian' : 'perbaikan';
}

function du_clean_kategori(string $value): string
{
    return $value === 'aset_medis' ? 'aset_medis' : 'rumah_tangga';
}

$flashSuccess = $_SESSION['du_flash_success'] ?? '';
$flashError = $_SESSION['du_flash_error'] ?? '';
unset($_SESSION['du_flash_success'], $_SESSION['du_flash_error']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_GET['du_action'] ?? '') === 'store') {
    try {
        $jenisOrder = du_clean_jenis_order((string)($_POST['jenis_order'] ?? 'perbaikan'));
        $kategori = du_clean_kategori((string)($_POST['kategori_divisi'] ?? 'rumah_tangga'));
        $unitName = trim((string)($_POST['unit_name'] ?? ''));
        $pelaporName = trim((string)($_POST['pelapor_name'] ?? ''));

        if ($unitName === '') {
            $unitName = trim((string)($user['unit_name'] ?? $user['unit'] ?? ''));
        }
        if ($pelaporName === '') {
            $pelaporName = trim((string)($user['full_name'] ?? $user['nama'] ?? $user['username'] ?? ''));
        }

        $payload = [
            'kategori_divisi' => $kategori,
            'jenis_order' => $jenisOrder,
            'judul_order' => trim((string)($_POST['judul_order'] ?? '')),
            'keluhan' => trim((string)($_POST['keluhan'] ?? '')),
            'unit_name' => $unitName,
            'lokasi' => trim((string)($_POST['lokasi'] ?? '')),
            'asset_name' => trim((string)($_POST['asset_name'] ?? '')),
            'asset_code' => trim((string)($_POST['asset_code'] ?? '')),
            'pelapor_name' => $pelaporName,
            'pelapor_phone' => trim((string)($_POST['pelapor_phone'] ?? '')),
            'prioritas' => du_clean_priority((string)($_POST['prioritas'] ?? 'normal')),
            'assigned_to' => trim((string)($_POST['assigned_to'] ?? '')),
            'source_app' => 'webapp_perawat',
            'source_user' => $user['nik'] ?? $user['username'] ?? '',
        ];

        if ($payload['judul_order'] === '') {
            throw new RuntimeException('Judul/laporan wajib diisi.');
        }
        if ($payload['keluhan'] === '') {
            throw new RuntimeException('Keluhan/deskripsi wajib diisi.');
        }

        if ($jenisOrder === 'order_penggantian') {
            $payload['pemesanan_barang'] = [
                'tanggal_pesan' => date('Y-m-d'),
                'jenis_barang' => $kategori === 'aset_medis' ? 'medis' : 'non_medis',
                'unit_pemesan' => $unitName,
                'nama_pemesan' => $pelaporName,
                'mengetahui_nama' => trim((string)($_POST['mengetahui_nama'] ?? '')),
                'mengetahui_jabatan' => trim((string)($_POST['mengetahui_jabatan'] ?? 'Kepala Unit')),
                'menyetujui_nama' => trim((string)($_POST['menyetujui_nama'] ?? '')),
                'menyetujui_jabatan' => trim((string)($_POST['menyetujui_jabatan'] ?? 'Kasubdiv / Divisi Umum')),
                'direktur_nama' => trim((string)($_POST['direktur_nama'] ?? 'Direktur RS BaliMéd Denpasar')),
                'direktur_jabatan' => trim((string)($_POST['direktur_jabatan'] ?? 'Direktur')),
                'status' => 'diajukan',
                'catatan' => trim((string)($_POST['catatan_pemesanan'] ?? 'Dibuat otomatis dari Work Order aplikasi Perawat.')),
                'use_direktur_stamp' => !empty($_POST['use_direktur_stamp']) ? 1 : 0,
                'items' => [
                    'nama_barang' => $_POST['pb_nama_barang'] ?? [],
                    'kebutuhan_per' => $_POST['pb_kebutuhan_per'] ?? [],
                    'sisa_stok' => $_POST['pb_sisa_stok'] ?? [],
                    'jumlah_order' => $_POST['pb_jumlah_order'] ?? [],
                    'tempat_pesanan' => $_POST['pb_tempat_pesanan'] ?? [],
                    'perkiraan_harga' => $_POST['pb_perkiraan_harga'] ?? [],
                    'keterangan' => $_POST['pb_keterangan'] ?? [],
                ],
            ];
        }

        $response = du_api_request($apiConfig, 'store', 'POST', $payload);
        $woNumber = $response['data']['wo_number'] ?? ('ID #' . ($response['id'] ?? '-'));
        $msg = 'Data berhasil dikirim ke Divisi Umum. Nomor WO: ' . $woNumber;
        if (!empty($response['pemesanan']['nomor_pemesanan'])) {
            $msg .= ' | Nomor Pemesanan: ' . $response['pemesanan']['nomor_pemesanan'];
        }
        $_SESSION['du_flash_success'] = $msg;
    } catch (Throwable $e) {
        $_SESSION['du_flash_error'] = $e->getMessage();
    }

    header('Location: index.php?module=distribusi_alat');
    exit;
}

$filters = [
    'status' => trim((string)($_GET['status'] ?? '')),
    'jenis_order' => trim((string)($_GET['jenis_order'] ?? '')),
    'q' => trim((string)($_GET['q'] ?? '')),
];

$remoteRows = [];
$stats = [];
$listError = '';
try {
    $list = du_api_request($apiConfig, 'list', 'GET', $filters);
    $remoteRows = is_array($list['data'] ?? null) ? $list['data'] : [];
    $stats = is_array($list['stats'] ?? null) ? $list['stats'] : [];
} catch (Throwable $e) {
    $listError = $e->getMessage();
}

$prefillName = trim((string)($user['full_name'] ?? $user['nama'] ?? $user['username'] ?? ''));
$prefillUnit = trim((string)($user['unit_name'] ?? $user['unit'] ?? ''));
?>
<div class="min-h-screen bg-slate-50 -m-4 md:-m-6 p-4 md:p-6">
    <div class="max-w-7xl mx-auto space-y-6">
        <div class="rounded-3xl overflow-hidden shadow-xl bg-gradient-to-br from-blue-700 via-indigo-700 to-cyan-600 text-white">
            <div class="p-6 md:p-8 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
                <div>
                    <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/15 border border-white/20 text-sm font-semibold mb-4">
                        <i class="fa-solid fa-link"></i> API Direct ke Divisi Umum
                    </div>
                    <h1 class="text-2xl md:text-4xl font-extrabold tracking-tight">Work Order Kerusakan & Pemesanan Barang</h1>
                    <p class="mt-3 text-blue-50 max-w-3xl">Input dari aplikasi Perawat akan langsung masuk ke web app Divisi Umum. Jika memilih <b>Order Penggantian</b>, form pemesanan barang akan muncul di bawah form Work Order.</p>
                </div>
                <div class="grid grid-cols-2 gap-3 min-w-[280px]">
                    <div class="rounded-2xl bg-white/15 border border-white/20 p-4">
                        <div class="text-3xl font-black"><?= (int)($stats['total'] ?? count($remoteRows)) ?></div>
                        <div class="text-sm text-blue-50">Total WO</div>
                    </div>
                    <div class="rounded-2xl bg-white/15 border border-white/20 p-4">
                        <div class="text-3xl font-black"><?= (int)($stats['penggantian_count'] ?? 0) ?></div>
                        <div class="text-sm text-blue-50">Order Penggantian</div>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($flashSuccess): ?>
            <div class="rounded-2xl border border-emerald-200 bg-emerald-50 px-5 py-4 text-emerald-800 font-semibold"><i class="fa-solid fa-circle-check mr-2"></i><?= du_e($flashSuccess) ?></div>
        <?php endif; ?>
        <?php if ($flashError): ?>
            <div class="rounded-2xl border border-red-200 bg-red-50 px-5 py-4 text-red-800 font-semibold"><i class="fa-solid fa-triangle-exclamation mr-2"></i><?= du_e($flashError) ?></div>
        <?php endif; ?>
        <?php if ($listError): ?>
            <div class="rounded-2xl border border-amber-200 bg-amber-50 px-5 py-4 text-amber-800"><b>Daftar WO belum bisa dibaca dari API:</b> <?= du_e($listError) ?></div>
        <?php endif; ?>

        <div class="bg-white rounded-3xl shadow-xl border border-slate-100 overflow-hidden">
            <div class="p-5 md:p-6 border-b border-slate-100 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                <div>
                    <div class="text-xs uppercase tracking-widest text-blue-600 font-black">Form Input</div>
                    <h2 class="text-xl md:text-2xl font-extrabold text-slate-800">Kirim Work Order ke Divisi Umum</h2>
                </div>
                <a href="<?= du_e(rtrim((string)du_api_config_value($apiConfig, 'base_url', 'https://drarnya.itcprogram.com'), '/') . '/work-orders') ?>" target="_blank" class="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-xl bg-slate-900 text-white font-bold hover:bg-slate-700">
                    <i class="fa-solid fa-up-right-from-square"></i> Buka Divisi Umum
                </a>
            </div>

            <form method="POST" action="index.php?module=distribusi_alat&du_action=store" class="p-5 md:p-6 space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Kategori</label>
                        <select name="kategori_divisi" id="kategori_divisi" class="w-full rounded-xl border-slate-200 px-4 py-3 bg-white border focus:ring-2 focus:ring-blue-500">
                            <option value="rumah_tangga">Rumah Tangga</option>
                            <option value="aset_medis">Aset Medis</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Jenis Order</label>
                        <select name="jenis_order" id="jenis_order" onchange="togglePemesananPanel()" class="w-full rounded-xl border-slate-200 px-4 py-3 bg-white border focus:ring-2 focus:ring-blue-500">
                            <option value="perbaikan">Perbaikan</option>
                            <option value="order_penggantian">Order Penggantian</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Unit Pelapor</label>
                        <?php if ($units): ?>
                            <select name="unit_name" class="w-full rounded-xl border-slate-200 px-4 py-3 bg-white border focus:ring-2 focus:ring-blue-500">
                                <option value="<?= du_e($prefillUnit) ?>"><?= du_e($prefillUnit ?: 'Pilih Unit') ?></option>
                                <?php foreach ($units as $unit): $name = $unit['name'] ?? $unit['unit_name'] ?? ''; if ($name === '') continue; ?>
                                    <option value="<?= du_e($name) ?>"><?= du_e($name) ?></option>
                                <?php endforeach; ?>
                            </select>
                        <?php else: ?>
                            <input type="text" name="unit_name" value="<?= du_e($prefillUnit) ?>" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Contoh: IGD">
                        <?php endif; ?>
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Prioritas</label>
                        <select name="prioritas" class="w-full rounded-xl border-slate-200 px-4 py-3 bg-white border focus:ring-2 focus:ring-blue-500">
                            <option value="rendah">Rendah</option>
                            <option value="normal" selected>Normal</option>
                            <option value="tinggi">Tinggi</option>
                            <option value="urgent">Urgent</option>
                        </select>
                    </div>
                    <div class="xl:col-span-2">
                        <label class="block text-sm font-bold text-slate-600 mb-1">Judul / Laporan *</label>
                        <input type="text" name="judul_order" required class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Contoh: AC tidak dingin / butuh penggantian bed">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Lokasi</label>
                        <input type="text" name="lokasi" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Contoh: Nurse station">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Aset / Alat / Barang</label>
                        <input type="text" name="asset_name" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Contoh: AC / Bed / Syringe pump">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Kode Aset</label>
                        <input type="text" name="asset_code" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Opsional">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Pelapor</label>
                        <input type="text" name="pelapor_name" value="<?= du_e($prefillName) ?>" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Nama pelapor">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">No. WA</label>
                        <input type="text" name="pelapor_phone" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="08xxxx">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Petugas</label>
                        <input type="text" name="assigned_to" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Opsional">
                    </div>
                    <div class="md:col-span-2 xl:col-span-4">
                        <label class="block text-sm font-bold text-slate-600 mb-1">Keluhan / Deskripsi *</label>
                        <textarea name="keluhan" rows="4" required class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Tulis detail kerusakan, kebutuhan penggantian, alasan, kondisi alat/barang..."></textarea>
                    </div>
                </div>

                <div id="pemesananPanel" class="hidden rounded-3xl border-2 border-dashed border-indigo-200 bg-indigo-50/60 p-5 md:p-6 space-y-5">
                    <div class="rounded-2xl bg-white border border-indigo-100 px-4 py-3 text-indigo-800 font-bold">
                        <i class="fa-solid fa-cart-plus mr-2"></i> Jenis order adalah <b>Order Penggantian</b>. Lanjutkan mengisi Form Pemesanan Barang di bawah ini.
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
                        <div>
                            <label class="block text-sm font-bold text-slate-600 mb-1">Mengetahui</label>
                            <input type="text" name="mengetahui_nama" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Nama Kepala Unit">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-600 mb-1">Jabatan Mengetahui</label>
                            <input type="text" name="mengetahui_jabatan" value="Kepala Unit" class="w-full rounded-xl border-slate-200 px-4 py-3 border">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-600 mb-1">Menyetujui</label>
                            <input type="text" name="menyetujui_nama" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Nama Kasubdiv / Divisi Umum">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-slate-600 mb-1">Jabatan Menyetujui</label>
                            <input type="text" name="menyetujui_jabatan" value="Kasubdiv / Divisi Umum" class="w-full rounded-xl border-slate-200 px-4 py-3 border">
                        </div>
                    </div>

                    <div class="overflow-x-auto rounded-2xl border border-indigo-100 bg-white">
                        <table class="min-w-full text-sm" id="pbTable">
                            <thead class="bg-slate-50 text-slate-600 uppercase text-xs">
                                <tr>
                                    <th class="px-3 py-3 text-left">Nama Barang</th>
                                    <th class="px-3 py-3 text-left">Kebutuhan Per</th>
                                    <th class="px-3 py-3 text-left">Sisa Stok</th>
                                    <th class="px-3 py-3 text-left">Jumlah Order</th>
                                    <th class="px-3 py-3 text-left">Tempat Pesanan</th>
                                    <th class="px-3 py-3 text-left">Perkiraan Harga</th>
                                    <th class="px-3 py-3 text-left">Ket.</th>
                                    <th class="px-3 py-3"></th>
                                </tr>
                            </thead>
                            <tbody id="pbRows">
                                <tr>
                                    <td class="p-2"><input name="pb_nama_barang[]" class="min-w-[180px] w-full rounded-lg border px-3 py-2" placeholder="Nama barang"></td>
                                    <td class="p-2"><input name="pb_kebutuhan_per[]" class="min-w-[120px] w-full rounded-lg border px-3 py-2" placeholder="Unit/ruangan"></td>
                                    <td class="p-2"><input name="pb_sisa_stok[]" class="min-w-[90px] w-full rounded-lg border px-3 py-2" placeholder="0"></td>
                                    <td class="p-2"><input name="pb_jumlah_order[]" type="number" step="0.01" class="min-w-[100px] w-full rounded-lg border px-3 py-2" placeholder="1"></td>
                                    <td class="p-2"><input name="pb_tempat_pesanan[]" class="min-w-[140px] w-full rounded-lg border px-3 py-2" placeholder="Opsional"></td>
                                    <td class="p-2"><input name="pb_perkiraan_harga[]" type="number" step="0.01" class="min-w-[130px] w-full rounded-lg border px-3 py-2" placeholder="0"></td>
                                    <td class="p-2"><input name="pb_keterangan[]" class="min-w-[150px] w-full rounded-lg border px-3 py-2" placeholder="Keterangan"></td>
                                    <td class="p-2"><button type="button" onclick="removePbRow(this)" class="px-3 py-2 rounded-lg bg-red-50 text-red-600"><i class="fa-solid fa-trash"></i></button></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                        <button type="button" onclick="addPbRow()" class="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-xl bg-indigo-600 text-white font-bold hover:bg-indigo-700"><i class="fa-solid fa-plus"></i> Tambah Baris Barang</button>
                        <label class="inline-flex items-center gap-2 text-sm font-semibold text-slate-700"><input type="checkbox" name="use_direktur_stamp" value="1" class="rounded"> Tempel stempel direktur jika dibutuhkan</label>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-slate-600 mb-1">Catatan Pemesanan</label>
                        <textarea name="catatan_pemesanan" rows="3" class="w-full rounded-xl border-slate-200 px-4 py-3 border" placeholder="Catatan tambahan untuk Divisi Umum / Rumah Tangga"></textarea>
                    </div>
                </div>

                <div class="flex flex-col md:flex-row justify-end gap-3 pt-2">
                    <button type="reset" class="px-5 py-3 rounded-xl border border-slate-200 text-slate-700 font-bold hover:bg-slate-50">Reset</button>
                    <button type="submit" class="px-6 py-3 rounded-xl bg-slate-900 text-white font-extrabold hover:bg-blue-700"><i class="fa-solid fa-paper-plane mr-2"></i>Kirim ke Divisi Umum</button>
                </div>
            </form>
        </div>

        <div class="bg-white rounded-3xl shadow-xl border border-slate-100 overflow-hidden">
            <div class="p-5 md:p-6 border-b border-slate-100">
                <div class="text-xs uppercase tracking-widest text-blue-600 font-black">Data API Divisi Umum</div>
                <h2 class="text-xl md:text-2xl font-extrabold text-slate-800">Daftar Work Order Terbaru</h2>
            </div>
            <form method="GET" action="index.php" class="p-5 md:p-6 border-b border-slate-100 grid grid-cols-1 md:grid-cols-4 gap-3">
                <input type="hidden" name="module" value="distribusi_alat">
                <input type="text" name="q" value="<?= du_e($filters['q']) ?>" class="rounded-xl border px-4 py-3" placeholder="Cari WO, unit, barang, pelapor...">
                <select name="status" class="rounded-xl border px-4 py-3">
                    <option value="">Semua Status</option>
                    <option value="open" <?= du_selected($filters['status'], 'open') ?>>Open</option>
                    <option value="in_progress" <?= du_selected($filters['status'], 'in_progress') ?>>In Progress</option>
                    <option value="done" <?= du_selected($filters['status'], 'done') ?>>Done</option>
                    <option value="cancelled" <?= du_selected($filters['status'], 'cancelled') ?>>Cancelled</option>
                </select>
                <select name="jenis_order" class="rounded-xl border px-4 py-3">
                    <option value="">Semua Jenis</option>
                    <option value="perbaikan" <?= du_selected($filters['jenis_order'], 'perbaikan') ?>>Perbaikan</option>
                    <option value="order_penggantian" <?= du_selected($filters['jenis_order'], 'order_penggantian') ?>>Order Penggantian</option>
                </select>
                <button class="rounded-xl bg-blue-600 text-white font-bold px-4 py-3"><i class="fa-solid fa-filter mr-2"></i>Filter</button>
            </form>
            <div class="overflow-x-auto">
                <table class="min-w-full text-sm">
                    <thead class="bg-slate-50 text-slate-500 uppercase text-xs">
                        <tr>
                            <th class="px-5 py-3 text-left">Nomor</th>
                            <th class="px-5 py-3 text-left">Jenis</th>
                            <th class="px-5 py-3 text-left">Judul</th>
                            <th class="px-5 py-3 text-left">Unit</th>
                            <th class="px-5 py-3 text-left">Aset/Barang</th>
                            <th class="px-5 py-3 text-left">Prioritas</th>
                            <th class="px-5 py-3 text-left">Status</th>
                            <th class="px-5 py-3 text-left">Tanggal</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <?php if (!$remoteRows): ?>
                            <tr><td colspan="8" class="px-5 py-8 text-center text-slate-500">Belum ada data atau API belum bisa dibaca.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($remoteRows as $row): ?>
                            <tr class="hover:bg-slate-50">
                                <td class="px-5 py-3 font-bold text-slate-800"><?= du_e($row['wo_number'] ?? '-') ?></td>
                                <td class="px-5 py-3"><?= du_e(($row['jenis_order'] ?? '') === 'order_penggantian' ? 'Order Penggantian' : 'Perbaikan') ?></td>
                                <td class="px-5 py-3"><?= du_e($row['judul_order'] ?? '-') ?></td>
                                <td class="px-5 py-3"><?= du_e($row['unit_name'] ?? '-') ?></td>
                                <td class="px-5 py-3"><?= du_e($row['asset_name'] ?? '-') ?></td>
                                <td class="px-5 py-3"><?= du_e($row['prioritas'] ?? '-') ?></td>
                                <td class="px-5 py-3"><span class="px-2 py-1 rounded-full bg-blue-50 text-blue-700 font-bold text-xs"><?= du_e($row['status'] ?? '-') ?></span></td>
                                <td class="px-5 py-3"><?= du_e(isset($row['created_at']) ? date('d/m/Y H:i', strtotime((string)$row['created_at'])) : '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
function togglePemesananPanel() {
    const jenis = document.getElementById('jenis_order')?.value || 'perbaikan';
    const panel = document.getElementById('pemesananPanel');
    if (!panel) return;
    panel.classList.toggle('hidden', jenis !== 'order_penggantian');
}

function addPbRow() {
    const tbody = document.getElementById('pbRows');
    if (!tbody) return;
    const first = tbody.querySelector('tr');
    const clone = first.cloneNode(true);
    clone.querySelectorAll('input').forEach(input => {
        if (input.type === 'number') input.value = '';
        else input.value = '';
    });
    tbody.appendChild(clone);
}

function removePbRow(btn) {
    const tbody = document.getElementById('pbRows');
    if (!tbody) return;
    if (tbody.querySelectorAll('tr').length <= 1) {
        btn.closest('tr').querySelectorAll('input').forEach(input => input.value = '');
        return;
    }
    btn.closest('tr').remove();
}

document.addEventListener('DOMContentLoaded', togglePemesananPanel);
</script>
