<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();
if (!isSuperAdmin()) jsonResponse(false, 'Akses ditolak.');
if (!verifyCsrfToken($_POST['csrf_token'] ?? $_GET['csrf'] ?? '')) jsonResponse(false, 'CSRF Error');

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$type = $_GET['type'] ?? $_POST['type'] ?? '';

if ($action === 'add' || $action === 'edit') {
    $id = intval($_POST['id'] ?? 0);
    $nama = sanitize($_POST['nama'] ?? '');
    if (!$nama) jsonResponse(false, 'Nama tidak boleh kosong.');

    if ($type === 'unit') {
        $kod = sanitize($_POST['kod'] ?? '');
        $warna = sanitize($_POST['warna'] ?? '#0d6efd');
        $ikon = sanitize($_POST['ikon'] ?? 'fas fa-building');
        $urutan = intval($_POST['urutan'] ?? 99);

        if ($action === 'add') {
            $stmt = $pdo->prepare("INSERT INTO unit (sektor_id, nama_unit, kod, warna, ikon, urutan, status) VALUES (1, ?, ?, ?, ?, ?, 1)");
            $stmt->execute([$nama, $kod, $warna, $ikon, $urutan]);
            jsonResponse(true, 'Unit berjaya ditambah.');
        } else {
            $stmt = $pdo->prepare("UPDATE unit SET nama_unit=?, kod=?, warna=?, ikon=?, urutan=? WHERE id=?");
            $stmt->execute([$nama, $kod, $warna, $ikon, $urutan, $id]);
            jsonResponse(true, 'Unit berjaya dikemaskini.');
        }
    } elseif ($type === 'subunit') {
        $unit_id = intval($_POST['unit_id'] ?? 0);
        if (!$unit_id) jsonResponse(false, 'Sila pilih unit.');

        if ($action === 'add') {
            $stmt = $pdo->prepare("INSERT INTO subunit (unit_id, nama_subunit, status) VALUES (?, ?, 1)");
            $stmt->execute([$unit_id, $nama]);
            jsonResponse(true, 'Subunit berjaya ditambah.');
        } else {
            $stmt = $pdo->prepare("UPDATE subunit SET unit_id=?, nama_subunit=? WHERE id=?");
            $stmt->execute([$unit_id, $nama, $id]);
            jsonResponse(true, 'Subunit berjaya dikemaskini.');
        }
    }
} elseif ($action === 'delete') {
    $id = intval($_GET['id'] ?? 0);
    if ($type === 'unit') {
        $pdo->prepare("DELETE FROM unit WHERE id=?")->execute([$id]);
        jsonResponse(true, 'Unit berjaya dipadam.');
    } elseif ($type === 'subunit') {
        $pdo->prepare("DELETE FROM subunit WHERE id=?")->execute([$id]);
        jsonResponse(true, 'Subunit berjaya dipadam.');
    }
}

jsonResponse(false, 'Tindakan tidak sah.');
