<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
checkAdmin();

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add' || $_POST['action'] === 'edit') {
            $id_diagnosa = $_POST['id_diagnosa'];
            $min_cf = (float)$_POST['min_cf'];
            $max_cf = (float)$_POST['max_cf'];
            $saran = $_POST['saran'];

            if ($_POST['action'] === 'add') {
                $stmt = $pdo->prepare("INSERT INTO solusi (id_diagnosa, min_cf, max_cf, saran) VALUES (?, ?, ?, ?)");
                $stmt->execute(array($id_diagnosa, $min_cf, $max_cf, $saran));
                setFlash('success', 'Solusi berhasil ditambahkan.');
            } else {
                $id = $_POST['id'];
                $stmt = $pdo->prepare("UPDATE solusi SET id_diagnosa = ?, min_cf = ?, max_cf = ?, saran = ? WHERE id = ?");
                $stmt->execute(array($id_diagnosa, $min_cf, $max_cf, $saran, $id));
                setFlash('success', 'Solusi berhasil diupdate.');
            }
        } elseif ($_POST['action'] === 'delete') {
            $id = $_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM solusi WHERE id = ?");
            $stmt->execute(array($id));
            setFlash('success', 'Solusi berhasil dihapus.');
        }
        redirect('data-solusi.php');
    }
}

$title = "Manajemen Solusi";
require_once 'includes/header.php';

// Pagination
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$totalRows = $pdo->query("SELECT COUNT(*) FROM solusi")->fetchColumn();
$totalPages = ceil($totalRows / $limit);

$stmt = $pdo->prepare("
    SELECT s.*, d.nama as diagnosa_nama 
    FROM solusi s 
    JOIN diagnosa d ON s.id_diagnosa = d.id 
    ORDER BY d.kode ASC, s.min_cf ASC 
    LIMIT :limit OFFSET :offset
");
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$solusi = $stmt->fetchAll();

$diagnosa_list = $pdo->query("SELECT * FROM diagnosa ORDER BY kode ASC")->fetchAll();
?>

<div class="flex justify-between items-center mb-8">
    <div>
        <h3 class="text-xl font-bold text-slate-800">Manajemen Solusi & Saran</h3>
        <p class="text-slate-500 text-sm">Kelola saran yang diberikan kepada siswa berdasarkan skor diagnosa.</p>
    </div>
    <button onclick="openModal('addModal')" class="btn-primary flex items-center gap-2">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
        Tambah Solusi
    </button>
</div>

<div class="card">
    <div class="overflow-x-auto">
        <table class="w-full text-left">
            <thead class="bg-slate-50 border-b border-slate-200">
                <tr>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Diagnosa</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Rentang CF</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Saran / Solusi</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest text-right">Aksi</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php if (empty($solusi)): ?>
                    <tr>
                        <td colspan="4" class="px-8 py-10 text-center text-slate-400 italic">Belum ada data solusi.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($solusi as $s): ?>
                        <tr class="hover:bg-slate-50 transition-colors text-sm">
                            <td class="px-8 py-4 font-bold text-slate-800"><?= $s['diagnosa_nama'] ?></td>
                            <td class="px-8 py-4">
                                <span class="font-mono font-bold bg-slate-100 px-2 py-1 rounded text-primary">
                                    <?= number_format($s['min_cf'], 2) ?> - <?= number_format($s['max_cf'], 2) ?>
                                </span>
                            </td>
                            <td class="px-8 py-4 text-slate-600 max-w-md"><?= $s['saran'] ?></td>
                            <td class="px-8 py-4 text-right space-x-2 whitespace-nowrap">
                                <button onclick="editSolusi(<?= htmlspecialchars(json_encode($s)) ?>)" class="font-bold text-primary hover:text-primary-dark">Edit</button>
                                <form action="" method="POST" class="inline" onsubmit="return confirm('Hapus solusi ini?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                    <button type="submit" class="font-bold text-red-500 hover:text-red-600">Hapus</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?= renderPagination($page, $totalPages, 'data-solusi.php?') ?>

<!-- Add/Edit Modal -->
<div id="addModal" class="fixed inset-0 bg-slate-900/50 hidden items-center justify-center z-50 p-6">
    <div class="bg-white rounded-3xl w-full max-w-lg p-8 shadow-2xl">
        <h3 id="modalTitle" class="text-xl font-bold text-slate-800 mb-6 font-primary">Tambah Solusi Baru</h3>
        <form action="" method="POST" class="space-y-5">
            <input type="hidden" name="action" id="formAction" value="add">
            <input type="hidden" name="id" id="solusiId">
            
            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Diagnosa</label>
                <select name="id_diagnosa" id="id_diagnosa" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all bg-white">
                    <?php foreach ($diagnosa_list as $dl): ?>
                        <option value="<?= $dl['id'] ?>"><?= $dl['nama'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Min CF</label>
                    <input type="number" step="0.01" name="min_cf" id="min_cf" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="0.00">
                </div>
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Max CF</label>
                    <input type="number" step="0.01" name="max_cf" id="max_cf" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="0.33">
                </div>
            </div>

            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Saran / Solusi</label>
                <textarea name="saran" id="saran" rows="4" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Berikan saran tindakan..."></textarea>
            </div>

            <div class="flex gap-4 pt-4">
                <button type="button" onclick="closeModal('addModal')" class="flex-1 py-3 text-sm font-bold text-slate-500 hover:bg-slate-50 rounded-xl transition-colors">Batal</button>
                <button type="submit" class="flex-1 btn-primary py-3 text-sm">Simpan</button>
            </div>
        </form>
    </div>
</div>

<script>
function openModal(id) {
    document.getElementById(id).classList.remove('hidden');
    document.getElementById(id).classList.add('flex');
}
function closeModal(id) {
    document.getElementById(id).classList.add('hidden');
    document.getElementById(id).classList.remove('flex');
    document.getElementById('formAction').value = 'add';
    document.getElementById('modalTitle').innerText = 'Tambah Solusi Baru';
}
function editSolusi(data) {
    document.getElementById('formAction').value = 'edit';
    document.getElementById('solusiId').value = data.id;
    document.getElementById('id_diagnosa').value = data.id_diagnosa;
    document.getElementById('min_cf').value = data.min_cf;
    document.getElementById('max_cf').value = data.max_cf;
    document.getElementById('saran').value = data.saran;
    document.getElementById('modalTitle').innerText = 'Edit Solusi';
    openModal('addModal');
}
</script>

<?php require_once 'includes/footer.php'; ?>
