<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';

date_default_timezone_set('Asia/Makassar');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if (!function_exists('esc')) {
    function esc($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function idm_angka($value)
{
    $value = str_replace(',', '.', trim((string)$value));
    return $value !== '' && is_numeric($value) ? (float)$value : null;
}

function idm_status_class($status)
{
    $map = [
        'Sangat Tertinggal' => 'danger',
        'Tertinggal' => 'warning',
        'Berkembang' => 'info',
        'Maju' => 'primary',
        'Mandiri' => 'success',
    ];

    return $map[$status] ?? 'neutral';
}

function idm_redirect($message)
{
    header('Location: idm.php?msg='.rawurlencode((string)$message));
    exit;
}

$statusOptions = [
    'Sangat Tertinggal',
    'Tertinggal',
    'Berkembang',
    'Maju',
    'Mandiri',
];

$act = $_GET['a'] ?? 'list';
if ($act === 'edit') {
    $act = 'form';
}

if (!isset($_SESSION['csrf_idm'])) {
    $_SESSION['csrf_idm'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_idm'];

$tableCheck = $mysqli->query("SHOW TABLES LIKE 'idm_desa'");
$tableReady = $tableCheck && $tableCheck->num_rows > 0;

$errorText = '';

if ($act === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $token = $_POST['csrf_token'] ?? '';

    if (!is_string($token) || !hash_equals($csrfToken, $token)) {
        idm_redirect('csrf');
    }

    if (!$tableReady || $id <= 0) {
        idm_redirect('notfound');
    }

    $stmt = $mysqli->prepare('DELETE FROM idm_desa WHERE id = ?');
    if (!$stmt) {
        idm_redirect('error');
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();
    $deleted = $stmt->affected_rows > 0;
    $stmt->close();

    idm_redirect($deleted ? 'deleted' : 'notfound');
}

if ($act === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $token = $_POST['csrf_token'] ?? '';
    $tahun = (int)($_POST['tahun'] ?? 0);
    $statusIdm = trim((string)($_POST['status_idm'] ?? ''));
    $skorIks = idm_angka($_POST['skor_iks'] ?? '');
    $skorIke = idm_angka($_POST['skor_ike'] ?? '');
    $skorIkl = idm_angka($_POST['skor_ikl'] ?? '');
    $skorIdmInput = idm_angka($_POST['skor_idm'] ?? '');
    $keterangan = trim((string)($_POST['keterangan'] ?? ''));

    if (!is_string($token) || !hash_equals($csrfToken, $token)) {
        $errorText = 'Token keamanan tidak valid. Muat ulang halaman.';
    } elseif (!$tableReady) {
        $errorText = 'Tabel IDM belum tersedia. Jalankan file database_idm_lembaga.sql terlebih dahulu.';
    } elseif ($tahun < 2000 || $tahun > 2100) {
        $errorText = 'Tahun IDM harus berada antara 2000 sampai 2100.';
    } elseif (!in_array($statusIdm, $statusOptions, true)) {
        $errorText = 'Status IDM tidak valid.';
    } elseif ($skorIks === null || $skorIke === null || $skorIkl === null) {
        $errorText = 'Nilai IKS, IKE, dan IKL wajib diisi.';
    } elseif (
        $skorIks < 0 || $skorIks > 1 ||
        $skorIke < 0 || $skorIke > 1 ||
        $skorIkl < 0 || $skorIkl > 1
    ) {
        $errorText = 'Nilai indeks harus berada pada rentang 0 sampai 1.';
    } else {
        $skorIdm = $skorIdmInput === null
            ? round(($skorIks + $skorIke + $skorIkl) / 3, 4)
            : $skorIdmInput;

        if ($skorIdm < 0 || $skorIdm > 1) {
            $errorText = 'Skor IDM harus berada pada rentang 0 sampai 1.';
        } elseif ($id > 0) {
            $stmt = $mysqli->prepare(
                'UPDATE idm_desa
                 SET tahun = ?, skor_idm = ?, status_idm = ?, skor_iks = ?, skor_ike = ?, skor_ikl = ?, keterangan = ?
                 WHERE id = ?'
            );

            if ($stmt) {
                $stmt->bind_param(
                    'idsdddsi',
                    $tahun,
                    $skorIdm,
                    $statusIdm,
                    $skorIks,
                    $skorIke,
                    $skorIkl,
                    $keterangan,
                    $id
                );

                if ($stmt->execute()) {
                    $stmt->close();
                    idm_redirect('updated');
                }

                $errorText = $stmt->errno === 1062
                    ? 'Data IDM untuk tahun tersebut sudah tersedia.'
                    : 'Data IDM gagal diperbarui: '.$stmt->error;
                $stmt->close();
            } else {
                $errorText = 'Query pembaruan gagal disiapkan: '.$mysqli->error;
            }
        } else {
            $stmt = $mysqli->prepare(
                'INSERT INTO idm_desa
                 (tahun, skor_idm, status_idm, skor_iks, skor_ike, skor_ikl, keterangan)
                 VALUES (?, ?, ?, ?, ?, ?, ?)'
            );

            if ($stmt) {
                $stmt->bind_param(
                    'idsddds',
                    $tahun,
                    $skorIdm,
                    $statusIdm,
                    $skorIks,
                    $skorIke,
                    $skorIkl,
                    $keterangan
                );

                if ($stmt->execute()) {
                    $stmt->close();
                    idm_redirect('saved');
                }

                $errorText = $stmt->errno === 1062
                    ? 'Data IDM untuk tahun tersebut sudah tersedia.'
                    : 'Data IDM gagal disimpan: '.$stmt->error;
                $stmt->close();
            } else {
                $errorText = 'Query penyimpanan gagal disiapkan: '.$mysqli->error;
            }
        }
    }

    if ($errorText !== '') {
        $act = 'form';
    }
}

$edit = null;
if ($act === 'form') {
    $editId = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
    if ($editId > 0 && $tableReady && $_SERVER['REQUEST_METHOD'] !== 'POST') {
        $stmt = $mysqli->prepare('SELECT * FROM idm_desa WHERE id = ? LIMIT 1');
        if ($stmt) {
            $stmt->bind_param('i', $editId);
            $stmt->execute();
            $edit = $stmt->get_result()->fetch_assoc();
            $stmt->close();
        }

        if (!$edit) {
            idm_redirect('notfound');
        }
    }
}

$rows = [];
if ($tableReady) {
    $result = $mysqli->query('SELECT * FROM idm_desa ORDER BY tahun DESC, id DESC');
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }
}

$latest = $rows[0] ?? null;
$messageMap = [
    'saved' => ['success', 'Data IDM berhasil disimpan.'],
    'updated' => ['success', 'Data IDM berhasil diperbarui.'],
    'deleted' => ['success', 'Data IDM berhasil dihapus.'],
    'notfound' => ['error', 'Data IDM tidak ditemukan.'],
    'csrf' => ['error', 'Token keamanan tidak valid. Silakan ulangi proses.'],
    'error' => ['error', 'Proses data IDM gagal dilakukan.'],
];
$message = $messageMap[$_GET['msg'] ?? ''] ?? null;

$formData = [
    'id' => 0,
    'tahun' => date('Y'),
    'skor_idm' => '',
    'status_idm' => 'Berkembang',
    'skor_iks' => '',
    'skor_ike' => '',
    'skor_ikl' => '',
    'keterangan' => '',
];

if ($edit) {
    $formData = array_merge($formData, $edit);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $act === 'form') {
    foreach (array_keys($formData) as $key) {
        if (isset($_POST[$key])) {
            $formData[$key] = $_POST[$key];
        }
    }
}

include __DIR__.'/../includes/header.php';
?>

<style>
.master-shell{animation:fadeIn .35s ease}
.master-head{margin-bottom:20px;display:flex;align-items:flex-start;justify-content:space-between;gap:18px}
.master-eyebrow{margin-bottom:4px;display:flex;align-items:center;gap:7px;color:var(--g600);font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.06em}
.master-head h2{margin:0;font-size:24px;line-height:1.25;letter-spacing:-.03em}
.master-head p{margin:6px 0 0;color:var(--muted);font-size:12px}
.master-actions{display:flex;gap:9px;flex-wrap:wrap}
.master-btn{min-height:40px;padding:0 15px;display:inline-flex;align-items:center;justify-content:center;gap:7px;border:0;border-radius:9px;font-size:12px;font-weight:800;transition:.2s}
.master-btn:hover{transform:translateY(-1px);box-shadow:var(--shadow)}
.master-btn-primary{color:#fff;background:linear-gradient(135deg,var(--g600),var(--g800))}
.master-btn-light{color:var(--g800);background:#fff;border:1px solid var(--line)}
.master-btn-danger{color:#b42318;background:#fff1f0;border:1px solid #ffd5d2}
.master-btn-small{min-height:32px;padding:0 10px;font-size:10px}
.master-stats{margin-bottom:18px;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
.master-stat{padding:17px;display:flex;align-items:center;gap:12px;background:#fff;border:1px solid var(--line);border-radius:12px;box-shadow:var(--shadow)}
.master-stat i{width:42px;height:42px;display:grid;place-items:center;color:var(--g700);background:var(--g100);border-radius:11px;font-size:20px}
.master-stat small,.master-stat strong{display:block}.master-stat small{color:var(--muted);font-size:9px;font-weight:700;text-transform:uppercase}.master-stat strong{margin-top:2px;font-size:17px}
.master-panel{background:#fff;border:1px solid var(--line);border-radius:13px;box-shadow:var(--shadow);overflow:hidden}
.master-panel-head{padding:17px 19px;display:flex;align-items:center;justify-content:space-between;gap:15px;border-bottom:1px solid var(--line)}
.master-panel-head h3{margin:0;font-size:15px}.master-panel-head p{margin:2px 0 0;color:var(--muted);font-size:10px}
.master-panel-body{padding:20px}
.master-alert{margin-bottom:16px;padding:12px 14px;display:flex;align-items:flex-start;gap:9px;border-radius:9px;font-size:11px;font-weight:600}
.master-alert-success{color:#08713b;background:#e9fff3;border:1px solid #c8f4db}.master-alert-error{color:#a1261c;background:#fff1f0;border:1px solid #ffd3cf}
.master-table-wrap{overflow-x:auto}.master-table{width:100%;min-width:900px;border-collapse:collapse}
.master-table th,.master-table td{padding:12px 13px;border-bottom:1px solid var(--line);text-align:left;vertical-align:middle}
.master-table th{color:var(--muted);background:var(--g50);font-size:9px;font-weight:800;text-transform:uppercase;letter-spacing:.04em}
.master-table td{font-size:11px}.master-table tbody tr:hover{background:#fbfffc}.master-table tbody tr:last-child td{border-bottom:0}
.score-main{font-size:16px;font-weight:800;color:var(--g800)}.score-components{display:flex;gap:5px;flex-wrap:wrap}.score-chip{padding:3px 6px;color:#4d5d55;background:#f1f6f3;border-radius:6px;font-size:8px;font-weight:700}
.status-badge{display:inline-flex;align-items:center;gap:5px;padding:5px 8px;border-radius:999px;font-size:9px;font-weight:800}.status-success{color:#08713b;background:#ddfbea}.status-primary{color:#155aa8;background:#e7f2ff}.status-info{color:#196b7c;background:#e6f9fc}.status-warning{color:#8a5a00;background:#fff3cf}.status-danger{color:#a1261c;background:#ffe7e4}.status-neutral{color:#59675f;background:#edf1ef}
.master-row-actions{display:flex;gap:6px;align-items:center}.master-row-actions form{margin:0}
.master-empty{padding:45px 20px;text-align:center;color:var(--muted)}.master-empty i{display:block;margin-bottom:8px;color:var(--g500);font-size:38px}
.master-form{display:grid;grid-template-columns:1fr 1fr;gap:17px}.master-field{display:grid;gap:6px}.master-field-full{grid-column:1/-1}.master-field label{font-size:11px;font-weight:800}.required{color:var(--red)}
.master-input{width:100%;min-height:43px;padding:10px 12px;color:var(--ink);background:#fff;border:1px solid var(--line);border-radius:9px;outline:none;font:inherit;transition:.2s}.master-input:focus{border-color:var(--g500);box-shadow:0 0 0 3px rgba(21,196,106,.13)}textarea.master-input{min-height:110px;resize:vertical}
.master-help{color:var(--muted);font-size:9px}.index-grid{grid-column:1/-1;display:grid;grid-template-columns:repeat(3,1fr);gap:12px;padding:15px;background:var(--g50);border:1px solid var(--g100);border-radius:11px}.calculate-row{grid-column:1/-1;display:flex;align-items:center;gap:10px;flex-wrap:wrap}.master-form-actions{grid-column:1/-1;padding-top:5px;display:flex;gap:9px;flex-wrap:wrap}
@media(max-width:900px){.master-stats{grid-template-columns:1fr 1fr}.master-form{grid-template-columns:1fr}.master-field-full,.index-grid,.calculate-row,.master-form-actions{grid-column:1}.index-grid{grid-template-columns:1fr}.master-head{flex-direction:column}.master-actions{width:100%}}
@media(max-width:560px){.master-stats{grid-template-columns:1fr}.master-btn{width:100%}.master-row-actions .master-btn{width:auto}}
</style>

<div class="master-shell">
    <div class="master-head">
        <div>
            <div class="master-eyebrow"><i class="ri-line-chart-fill"></i> Data Desa</div>
            <h2><?= $act === 'form' ? ((int)$formData['id'] > 0 ? 'Edit Data IDM' : 'Tambah Data IDM') : 'Indeks Desa Membangun' ?></h2>
            <p>Kelola nilai IDM, ketahanan sosial, ekonomi, dan lingkungan setiap tahun.</p>
        </div>
        <div class="master-actions">
            <?php if ($act === 'form'): ?>
                <a class="master-btn master-btn-light" href="idm.php"><i class="ri-arrow-left-line"></i> Kembali</a>
            <?php else: ?>
                <a class="master-btn master-btn-primary" href="idm.php?a=form"><i class="ri-add-circle-fill"></i> Tambah Data IDM</a>
            <?php endif; ?>
        </div>
    </div>

    <?php if (!$tableReady): ?>
        <div class="master-alert master-alert-error"><i class="ri-database-2-line"></i><span>Tabel <strong>idm_desa</strong> belum tersedia. Jalankan <strong>database_idm_lembaga.sql</strong> pada database terlebih dahulu.</span></div>
    <?php endif; ?>
    <?php if ($message): ?>
        <div class="master-alert master-alert-<?= esc($message[0]) ?>"><i class="<?= $message[0] === 'success' ? 'ri-checkbox-circle-fill' : 'ri-error-warning-fill' ?>"></i><span><?= esc($message[1]) ?></span></div>
    <?php endif; ?>
    <?php if ($errorText !== ''): ?>
        <div class="master-alert master-alert-error"><i class="ri-error-warning-fill"></i><span><?= esc($errorText) ?></span></div>
    <?php endif; ?>

    <?php if ($act !== 'form'): ?>
        <div class="master-stats">
            <div class="master-stat"><i class="ri-database-2-fill"></i><div><small>Total Data</small><strong><?= count($rows) ?> Tahun</strong></div></div>
            <div class="master-stat"><i class="ri-calendar-check-fill"></i><div><small>Tahun Terbaru</small><strong><?= $latest ? (int)$latest['tahun'] : '-' ?></strong></div></div>
            <div class="master-stat"><i class="ri-speed-up-fill"></i><div><small>Skor Terbaru</small><strong><?= $latest ? number_format((float)$latest['skor_idm'], 4, ',', '.') : '0,0000' ?></strong></div></div>
            <div class="master-stat"><i class="ri-award-fill"></i><div><small>Status Terbaru</small><strong><?= $latest ? esc($latest['status_idm']) : '-' ?></strong></div></div>
        </div>

        <div class="master-panel">
            <div class="master-panel-head"><div><h3>Riwayat Data IDM</h3><p>Data diurutkan dari tahun terbaru.</p></div></div>
            <?php if (!$rows): ?>
                <div class="master-empty"><i class="ri-line-chart-line"></i><strong>Belum ada data IDM</strong><p>Tambahkan data IDM tahunan melalui tombol di atas.</p></div>
            <?php else: ?>
                <div class="master-table-wrap">
                    <table class="master-table">
                        <thead><tr><th>Tahun</th><th>Skor IDM</th><th>Komponen Indeks</th><th>Status</th><th>Keterangan</th><th>Aksi</th></tr></thead>
                        <tbody>
                        <?php foreach ($rows as $row): ?>
                            <tr>
                                <td><strong><?= (int)$row['tahun'] ?></strong></td>
                                <td><span class="score-main"><?= number_format((float)$row['skor_idm'], 4, ',', '.') ?></span></td>
                                <td><div class="score-components"><span class="score-chip">IKS <?= number_format((float)$row['skor_iks'], 4, ',', '.') ?></span><span class="score-chip">IKE <?= number_format((float)$row['skor_ike'], 4, ',', '.') ?></span><span class="score-chip">IKL <?= number_format((float)$row['skor_ikl'], 4, ',', '.') ?></span></div></td>
                                <td><span class="status-badge status-<?= esc(idm_status_class($row['status_idm'])) ?>"><i class="ri-checkbox-blank-circle-fill"></i><?= esc($row['status_idm']) ?></span></td>
                                <td><?= $row['keterangan'] !== '' ? esc($row['keterangan']) : '-' ?></td>
                                <td><div class="master-row-actions"><a class="master-btn master-btn-light master-btn-small" href="idm.php?a=form&id=<?= (int)$row['id'] ?>"><i class="ri-edit-2-fill"></i>Edit</a><form method="post" action="idm.php?a=delete" onsubmit="return confirm('Yakin ingin menghapus data IDM tahun ini?');"><input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><button class="master-btn master-btn-danger master-btn-small" type="submit"><i class="ri-delete-bin-6-fill"></i>Hapus</button></form></div></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="master-panel">
            <div class="master-panel-head"><div><h3><?= (int)$formData['id'] > 0 ? 'Perbarui Data IDM' : 'Form Data IDM Baru' ?></h3><p>Isi nilai indeks dalam rentang 0 sampai 1.</p></div></div>
            <div class="master-panel-body">
                <form class="master-form" method="post" action="idm.php?a=save" id="idmForm">
                    <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
                    <input type="hidden" name="id" value="<?= (int)$formData['id'] ?>">

                    <div class="master-field"><label for="tahun">Tahun <span class="required">*</span></label><input class="master-input" id="tahun" name="tahun" type="number" min="2000" max="2100" value="<?= esc($formData['tahun']) ?>" required></div>
                    <div class="master-field"><label for="statusIdm">Status IDM <span class="required">*</span></label><select class="master-input" id="statusIdm" name="status_idm" required><?php foreach ($statusOptions as $option): ?><option value="<?= esc($option) ?>" <?= $formData['status_idm'] === $option ? 'selected' : '' ?>><?= esc($option) ?></option><?php endforeach; ?></select></div>

                    <div class="index-grid">
                        <div class="master-field"><label for="skorIks">IKS — Ketahanan Sosial <span class="required">*</span></label><input class="master-input index-component" id="skorIks" name="skor_iks" type="number" min="0" max="1" step="0.0001" value="<?= esc($formData['skor_iks']) ?>" placeholder="0.0000" required></div>
                        <div class="master-field"><label for="skorIke">IKE — Ketahanan Ekonomi <span class="required">*</span></label><input class="master-input index-component" id="skorIke" name="skor_ike" type="number" min="0" max="1" step="0.0001" value="<?= esc($formData['skor_ike']) ?>" placeholder="0.0000" required></div>
                        <div class="master-field"><label for="skorIkl">IKL — Ketahanan Lingkungan <span class="required">*</span></label><input class="master-input index-component" id="skorIkl" name="skor_ikl" type="number" min="0" max="1" step="0.0001" value="<?= esc($formData['skor_ikl']) ?>" placeholder="0.0000" required></div>
                        <div class="calculate-row"><button class="master-btn master-btn-light" type="button" id="calculateIdm"><i class="ri-calculator-fill"></i>Hitung Rata-rata</button><span class="master-help">Skor IDM dapat dihitung dari rata-rata IKS, IKE, dan IKL.</span></div>
                    </div>

                    <div class="master-field master-field-full"><label for="skorIdm">Skor IDM</label><input class="master-input" id="skorIdm" name="skor_idm" type="number" min="0" max="1" step="0.0001" value="<?= esc($formData['skor_idm']) ?>" placeholder="Kosongkan agar dihitung otomatis"><span class="master-help">Kosongkan untuk menghitung otomatis dari tiga komponen indeks.</span></div>
                    <div class="master-field master-field-full"><label for="keterangan">Keterangan</label><textarea class="master-input" id="keterangan" name="keterangan" placeholder="Catatan atau penjelasan capaian IDM"><?= esc($formData['keterangan']) ?></textarea></div>

                    <div class="master-form-actions"><button class="master-btn master-btn-primary" type="submit" <?= !$tableReady ? 'disabled' : '' ?>><i class="ri-save-3-fill"></i><?= (int)$formData['id'] > 0 ? 'Perbarui Data' : 'Simpan Data' ?></button><a class="master-btn master-btn-light" href="idm.php"><i class="ri-close-circle-fill"></i>Batal</a></div>
                </form>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
(() => {
    const button = document.getElementById('calculateIdm');
    const score = document.getElementById('skorIdm');
    const components = Array.from(document.querySelectorAll('.index-component'));
    button?.addEventListener('click', () => {
        const values = components.map((input) => Number.parseFloat(input.value));
        if (values.some((value) => Number.isNaN(value) || value < 0 || value > 1)) {
            window.alert('Isi nilai IKS, IKE, dan IKL antara 0 sampai 1 terlebih dahulu.');
            return;
        }
        score.value = (values.reduce((total, value) => total + value, 0) / values.length).toFixed(4);
    });
})();
</script>

<?php include __DIR__.'/../includes/footer.php'; ?>
