<?php
// File: admin/credit_settings.php
session_start();
require '../includes/db_connect.php';
require '../includes/functions.php';

if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit; }

// --- ACTIONS ---
if (isset($_GET['action'])) {
    if ($_GET['action'] == 'delete_tenor' && isset($_GET['id'])) {
        $pdo->prepare("DELETE FROM kredit_tenor WHERE id = ?")->execute([$_GET['id']]);
        header("Location: credit_settings.php"); exit;
    }
    if ($_GET['action'] == 'delete_ins' && isset($_GET['id'])) {
        $pdo->prepare("DELETE FROM rate_asuransi WHERE id = ?")->execute([$_GET['id']]);
        header("Location: credit_settings.php"); exit;
    }
}

// --- SAVE ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // 1. Update Umum
        $stmt = $pdo->prepare("UPDATE kredit_umum SET rate_provisi = ?, biaya_fiducia = ? WHERE id = 1");
        $stmt->execute([$_POST['rate_provisi'], $_POST['biaya_fiducia']]);

        // 2. Update Tenor (Bunga & ACP)
        if(isset($_POST['tenors']) && is_array($_POST['tenors'])) {
            foreach ($_POST['tenors'] as $t) {
                $id = $t['id'] ?? null;
                $active = isset($t['active']) ? 1 : 0;
                if (empty($t['tahun'])) continue;

                if ($id) {
                    $pdo->prepare("UPDATE kredit_tenor SET tenor_tahun=?, bunga_per_tahun=?, rate_acp=?, biaya_admin=?, is_active=? WHERE id=?")
                        ->execute([$t['tahun'], $t['bunga'], $t['acp'], $t['admin'], $active, $id]);
                } else {
                    $pdo->prepare("INSERT INTO kredit_tenor (tenor_tahun, bunga_per_tahun, rate_acp, biaya_admin, is_active) VALUES (?, ?, ?, ?, ?)")
                        ->execute([$t['tahun'], $t['bunga'], $t['acp'], $t['admin'], $active]);
                }
            }
        }

        // 3. Update Asuransi (Tiering)
        if(isset($_POST['insurance']) && is_array($_POST['insurance'])) {
            foreach ($_POST['insurance'] as $ins) {
                $id = $ins['id'] ?? null;
                // Bersihkan format angka
                $min = str_replace(['.',','], '', $ins['min']);
                $max = str_replace(['.',','], '', $ins['max']);
                
                if ($id) {
                    $pdo->prepare("UPDATE rate_asuransi SET min_price=?, max_price=?, tenor_1=?, tenor_2=?, tenor_3=?, tenor_4=?, tenor_5=? WHERE id=?")
                        ->execute([$min, $max, $ins['t1'], $ins['t2'], $ins['t3'], $ins['t4'], $ins['t5'], $id]);
                } else {
                    $pdo->prepare("INSERT INTO rate_asuransi (min_price, max_price, tenor_1, tenor_2, tenor_3, tenor_4, tenor_5) VALUES (?, ?, ?, ?, ?, ?, ?)")
                        ->execute([$min, $max, $ins['t1'], $ins['t2'], $ins['t3'], $ins['t4'], $ins['t5']]);
                }
            }
        }

        $success = "Setting Kredit Berhasil Diupdate!";
    } catch (Exception $e) { $success = "Error: " . $e->getMessage(); }
}

$creditData = getCreditData($pdo);
$umum = $creditData['umum'];
$tenors = $creditData['tenors'];
$insurance = $creditData['insurance']; // Data Asuransi

$page_title = 'Setting Kredit';
require 'includes/header.php';
?>

<div class="flex justify-between items-center mb-6">
    <h2 class="text-3xl font-bold text-gray-800">Parameter Simulasi Kredit</h2>
</div>

<?php if(isset($success)): ?>
    <div class="<?= strpos($success,'Error')!==false?'bg-red-100 text-red-700':'bg-green-100 text-green-700' ?> p-4 rounded mb-6 font-bold"><?= $success ?></div>
<?php endif; ?>

<form method="POST">
    <!-- 1. SETTING UMUM -->
    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200 mb-8">
        <h3 class="text-lg font-bold mb-4 text-gray-800 border-b pb-2">1. Setting Umum</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-bold mb-2">Rate Provisi (Desimal)</label>
                <input type="number" step="0.0001" name="rate_provisi" value="<?= $umum['rate_provisi'] ?>" class="w-full p-2 border rounded">
                <p class="text-xs text-gray-500 mt-1">Contoh: 1% = 0.01</p>
            </div>
            <div>
                <label class="block text-sm font-bold mb-2">Biaya Fiducia (Rp)</label>
                <input type="number" name="biaya_fiducia" value="<?= $umum['biaya_fiducia'] ?>" class="w-full p-2 border rounded">
            </div>
        </div>
    </div>

    <!-- 2. SETTING TENOR & BUNGA & ACP -->
    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200 mb-8">
        <div class="flex justify-between items-center mb-4 border-b pb-2">
            <h3 class="text-lg font-bold text-gray-800">2. Rate Bunga & ACP per Tenor</h3>
            <button type="button" onclick="addTenorRow()" class="bg-blue-100 text-blue-700 px-3 py-1 rounded text-sm font-bold">+ Tambah</button>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left text-sm">
                <thead class="bg-gray-50 uppercase text-xs">
                    <tr><th class="p-2">Tenor (Thn)</th><th class="p-2">Bunga (Flat/Thn)</th><th class="p-2">Rate ACP</th><th class="p-2">Admin (Rp)</th><th class="p-2">Aktif</th><th class="p-2"></th></tr>
                </thead>
                <tbody id="tenor-body">
                    <?php foreach($tenors as $i => $t): ?>
                    <tr class="border-b">
                        <td class="p-2"><input type="hidden" name="tenors[<?= $i ?>][id]" value="<?= $t['id'] ?>"><input type="number" name="tenors[<?= $i ?>][tahun]" value="<?= $t['tenor_tahun'] ?>" class="w-16 p-1 border rounded text-center"></td>
                        <td class="p-2"><input type="number" step="0.0001" name="tenors[<?= $i ?>][bunga]" value="<?= $t['bunga_per_tahun'] ?>" class="w-full p-1 border rounded"></td>
                        <td class="p-2"><input type="number" step="0.0001" name="tenors[<?= $i ?>][acp]" value="<?= $t['rate_acp'] ?>" class="w-full p-1 border rounded bg-yellow-50"></td>
                        <td class="p-2"><input type="number" name="tenors[<?= $i ?>][admin]" value="<?= $t['biaya_admin'] ?>" class="w-full p-1 border rounded"></td>
                        <td class="p-2 text-center"><input type="checkbox" name="tenors[<?= $i ?>][active]" value="1" <?= $t['is_active']?'checked':'' ?>></td>
                        <td class="p-2"><a href="?action=delete_tenor&id=<?= $t['id'] ?>" onclick="return confirm('Hapus?')" class="text-red-500">Hapus</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <p class="text-xs text-gray-500 mt-2">* Masukkan Rate dalam desimal (Contoh: 5% = 0.05)</p>
    </div>

    <!-- 3. SETTING RATE ASURANSI (TIERING) -->
    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200 mb-8">
        <div class="flex justify-between items-center mb-4 border-b pb-2">
            <h3 class="text-lg font-bold text-gray-800">3. Rate Asuransi (Tiering OTR)</h3>
            <button type="button" onclick="addInsRow()" class="bg-blue-100 text-blue-700 px-3 py-1 rounded text-sm font-bold">+ Tambah Tier</button>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left text-sm">
                <thead class="bg-gray-50 uppercase text-xs">
                    <tr>
                        <th class="p-2">Range OTR (Min - Max)</th>
                        <th class="p-2">Thn 1 (%)</th>
                        <th class="p-2">Thn 2 (%)</th>
                        <th class="p-2">Thn 3 (%)</th>
                        <th class="p-2">Thn 4 (%)</th>
                        <th class="p-2">Thn 5 (%)</th>
                        <th class="p-2"></th>
                    </tr>
                </thead>
                <tbody id="ins-body">
                    <?php foreach($insurance as $k => $ins): ?>
                    <tr class="border-b">
                        <td class="p-2">
                            <input type="hidden" name="insurance[<?= $k ?>][id]" value="<?= $ins['id'] ?>">
                            <div class="flex gap-1">
                                <input type="text" name="insurance[<?= $k ?>][min]" value="<?= number_format($ins['min_price'],0,',','.') ?>" class="w-24 p-1 border rounded text-xs" placeholder="Min">
                                <span>-</span>
                                <input type="text" name="insurance[<?= $k ?>][max]" value="<?= number_format($ins['max_price'],0,',','.') ?>" class="w-24 p-1 border rounded text-xs" placeholder="Max">
                            </div>
                        </td>
                        <td class="p-2"><input type="number" step="0.0001" name="insurance[<?= $k ?>][t1]" value="<?= $ins['tenor_1'] ?>" class="w-16 p-1 border rounded"></td>
                        <td class="p-2"><input type="number" step="0.0001" name="insurance[<?= $k ?>][t2]" value="<?= $ins['tenor_2'] ?>" class="w-16 p-1 border rounded"></td>
                        <td class="p-2"><input type="number" step="0.0001" name="insurance[<?= $k ?>][t3]" value="<?= $ins['tenor_3'] ?>" class="w-16 p-1 border rounded"></td>
                        <td class="p-2"><input type="number" step="0.0001" name="insurance[<?= $k ?>][t4]" value="<?= $ins['tenor_4'] ?>" class="w-16 p-1 border rounded"></td>
                        <td class="p-2"><input type="number" step="0.0001" name="insurance[<?= $k ?>][t5]" value="<?= $ins['tenor_5'] ?>" class="w-16 p-1 border rounded"></td>
                        <td class="p-2"><a href="?action=delete_ins&id=<?= $ins['id'] ?>" onclick="return confirm('Hapus Tier?')" class="text-red-500">X</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <p class="text-xs text-gray-500 mt-2">* Masukkan Rate Asuransi dalam PERSEN (Contoh: 2.47 = 2.47%)</p>
    </div>

    <div class="fixed bottom-6 right-6 z-40">
        <button type="submit" class="bg-blue-600 text-white font-bold py-3 px-8 rounded-full shadow-xl hover:bg-blue-700">Simpan Semua</button>
    </div>
</form>

<script>
function addTenorRow() {
    const idx = Date.now();
    const row = `<tr class="border-b"><td class="p-2"><input type="number" name="tenors[${idx}][tahun]" class="w-16 p-1 border rounded text-center"></td><td class="p-2"><input type="number" step="0.0001" name="tenors[${idx}][bunga]" class="w-full p-1 border rounded"></td><td class="p-2"><input type="number" step="0.0001" name="tenors[${idx}][acp]" class="w-full p-1 border rounded bg-yellow-50"></td><td class="p-2"><input type="number" name="tenors[${idx}][admin]" class="w-full p-1 border rounded"></td><td class="p-2 text-center"><input type="checkbox" name="tenors[${idx}][active]" value="1" checked></td><td class="p-2"><button type="button" onclick="this.closest('tr').remove()" class="text-red-500">Hapus</button></td></tr>`;
    document.getElementById('tenor-body').insertAdjacentHTML('beforeend', row);
}
function addInsRow() {
    const idx = Date.now();
    const row = `<tr class="border-b"><td class="p-2"><div class="flex gap-1"><input type="text" name="insurance[${idx}][min]" class="w-24 p-1 border rounded text-xs" placeholder="Min"><span class="text-gray-400">-</span><input type="text" name="insurance[${idx}][max]" class="w-24 p-1 border rounded text-xs" placeholder="Max"></div></td><td class="p-2"><input type="number" step="0.0001" name="insurance[${idx}][t1]" class="w-16 p-1 border rounded"></td><td class="p-2"><input type="number" step="0.0001" name="insurance[${idx}][t2]" class="w-16 p-1 border rounded"></td><td class="p-2"><input type="number" step="0.0001" name="insurance[${idx}][t3]" class="w-16 p-1 border rounded"></td><td class="p-2"><input type="number" step="0.0001" name="insurance[${idx}][t4]" class="w-16 p-1 border rounded"></td><td class="p-2"><input type="number" step="0.0001" name="insurance[${idx}][t5]" class="w-16 p-1 border rounded"></td><td class="p-2"><button type="button" onclick="this.closest('tr').remove()" class="text-red-500">X</button></td></tr>`;
    document.getElementById('ins-body').insertAdjacentHTML('beforeend', row);
}
</script>

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