<?php
/**
 * Migration: Create Simpanan Settings Tables
 * Creates tables for monthly savings settings (Wajib & Sukarela)
 */

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

requireAdmin();
$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Create Simpanan Wajib Pengaturan table
        $db->exec("CREATE TABLE IF NOT EXISTS simpanan_wajib_pengaturan (
            bulan VARCHAR(7) NOT NULL PRIMARY KEY,
            nominal DECIMAL(15,2) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_bulan (bulan)
        ) ENGINE=InnoDB CHARSET=utf8mb4");
        
        // Create Simpanan Sukarela Pengaturan table
        $db->exec("CREATE TABLE IF NOT EXISTS simpanan_sukarela_pengaturan (
            bulan VARCHAR(7) NOT NULL PRIMARY KEY,
            nominal DECIMAL(15,2) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_bulan (bulan)
        ) ENGINE=InnoDB CHARSET=utf8mb4");

        // Insert default settings if not exist
        $bulanIni = date('Y-m');
        
        // Default Simpanan Wajib
        try {
            $chk = $db->prepare("SELECT COUNT(*) FROM simpanan_wajib_pengaturan WHERE bulan = ?");
            $chk->execute([$bulanIni]);
            if ($chk->fetchColumn() == 0) {
                $stmt = $db->prepare("INSERT INTO simpanan_wajib_pengaturan (bulan, nominal) VALUES (?, ?)");
                $stmt->execute([$bulanIni, 50000]);
            }
        } catch (Exception $e) {}
        
        // Default Simpanan Sukarela
        try {
            $chk = $db->prepare("SELECT COUNT(*) FROM simpanan_sukarela_pengaturan WHERE bulan = ?");
            $chk->execute([$bulanIni]);
            if ($chk->fetchColumn() == 0) {
                $stmt = $db->prepare("INSERT INTO simpanan_sukarela_pengaturan (bulan, nominal) VALUES (?, ?)");
                $stmt->execute([$bulanIni, 100000]);
            }
        } catch (Exception $e) {}

        setFlash('success', '✓ Tabel pengaturan simpanan berhasil dibuat/diupdate.');
        header('Location: ' . (isset($_GET['return']) ? $_GET['return'] : 'pengaturan.php'));
        exit;
        
    } catch (Exception $e) {
        setFlash('danger', '✗ Gagal membuat tabel: ' . $e->getMessage());
        header('Location: ' . (isset($_GET['return']) ? $_GET['return'] : 'pengaturan.php'));
        exit;
    }
}

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

<div class="container">
    <div class="card" style="max-width: 600px; margin: 40px auto;">
        <div class="card-header" style="background: var(--warning-100); border-color: var(--warning-200);">
            <h3 style="margin: 0; color: var(--warning-700);">
                <i class="fas fa-database" style="margin-right: 8px;"></i>
                Inisialisasi Database - Pengaturan Simpanan
            </h3>
        </div>
        <div class="card-body">
            <p style="margin-bottom: 20px; line-height: 1.6;">
                Migrasi ini akan membuat/memperbarui tabel-tabel berikut:
            </p>
            <ul style="margin-bottom: 20px; padding-left: 20px;">
                <li><strong>simpanan_wajib_pengaturan</strong> - Pengaturan nominal simpanan wajib per bulan</li>
                <li><strong>simpanan_sukarela_pengaturan</strong> - Pengaturan nominal simpanan sukarela per bulan</li>
            </ul>
            <p style="color: var(--gray-600); font-size: 0.9rem; margin-bottom: 20px;">
                Sistem akan otomatis menambahkan pengaturan default untuk bulan ini jika belum ada.
            </p>
        </div>
        <div class="card-footer">
            <form method="POST" onsubmit="return confirm('Lanjutkan inisialisasi database?');" style="display: flex; gap: 10px;">
                <button type="submit" class="btn btn-primary" style="flex: 1;">
                    <i class="fas fa-check-circle"></i> Lanjutkan
                </button>
                <a href="<?= isset($_GET['return']) ? htmlspecialchars($_GET['return']) : '../index.php' ?>" class="btn btn-outline" style="flex: 1; text-align: center;">
                    <i class="fas fa-times-circle"></i> Batal
                </a>
            </form>
        </div>
    </div>
</div>

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