<?php
require_once '../config.php';
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$settings_file = __DIR__ . '/../website_settings.json';
$default_settings = [
    'nama_spam' => 'SPAM Desa Gemuruh',
    'alamat_spam' => 'Desa Gemuruh',
    'nomor_hp' => '',
    'logo_url' => '',
    'judul_hero' => 'Selamat Datang di SPAM Desa Gemuruh',
    'subjudul_hero' => 'Sistem Penyediaan Air Minum berbasis masyarakat.',
    'warna_utama' => '#3A7CA5',
    'warna_utama_gelap' => '#2C5F7D',
    'fonnte_token' => '',
    'fonnte_device' => '',
    'format_pesan_tagihan' => "Halo {nama},\n\nTagihan air bulan {bulan} {tahun}:\n- Pemakaian air: {pemakaian} m³\n- Abonemen: {abonemen}\nTotal yang harus dibayar: {total}\n\nSegera bayar sebelum tgl 10 bulan berikutnya untuk menghindari denda.\nKunjungi spam.desagemuruh.id untuk informasi tagihan, riwayat pemakaian dan pembayaran, serta laporan keuangan.\n\nTerima kasih,\nSPAM Tirtha Kedawung Desa Gemuruh",
    'format_pesan_lunas' => "Halo {nama},\n\nPembayaran tagihan air bulan {bulan} {tahun} sebesar {total} telah kami terima dan catat dalam sistem.\n\nKunjungi spam.desagemuruh.id untuk informasi tagihan, riwayat pemakaian dan pembayaran, serta laporan keuangan.\n\nTerima kasih,\nSPAM Tirtha Kedawung Desa Gemuruh"
];

// Baca pengaturan yang ada
$settings = $default_settings;
if (file_exists($settings_file)) {
    $raw = @file_get_contents($settings_file);
    $decoded = json_decode($raw, true);
    if (is_array($decoded)) {
        $settings = array_merge($default_settings, $decoded);
    }
}

$success = '';
$error = '';
$test_wa_result = '';

// Handle Test Kirim WA
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_wa'])) {
    $token = trim($_POST['fonnte_token']);
    $nomor_test = trim($_POST['nomor_test']);
    $pesan_test = trim($_POST['pesan_test']);
    
    if (empty($token) || empty($nomor_test)) {
        $test_wa_result = '<div class="alert alert-warning" style="font-size:0.85rem; border-radius:10px;">Token dan nomor HP harus diisi!</div>';
    } else {
        $nomor_test = preg_replace('/^0/', '62', $nomor_test);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.fonnte.com/send",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => array('target' => $nomor_test, 'message' => $pesan_test),
            CURLOPT_HTTPHEADER => array("Authorization: $token"),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $test_wa_result = '<div class="alert alert-info" style="font-size:0.85rem; border-radius:10px;"><b>Respon Fonnte:</b><br><pre style="margin:0; font-size:0.8rem;">' . htmlspecialchars($response) . '</pre></div>';
    }
}

// Handle Simpan Pengaturan
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['simpan_pengaturan'])) {
    $new_settings = [
        'nama_spam' => trim($_POST['nama_spam']),
        'alamat_spam' => trim($_POST['alamat_spam']),
        'nomor_hp' => trim($_POST['nomor_hp']),
        'logo_url' => $settings['logo_url'],
        'judul_hero' => trim($_POST['judul_hero']),
        'subjudul_hero' => trim($_POST['subjudul_hero']),
        'warna_utama' => trim($_POST['warna_utama']),
        'warna_utama_gelap' => trim($_POST['warna_utama_gelap']),
        'fonnte_token' => trim($_POST['fonnte_token']),
        'fonnte_device' => trim($_POST['fonnte_device']),
        'format_pesan_tagihan' => trim($_POST['format_pesan_tagihan']),
        'format_pesan_lunas' => trim($_POST['format_pesan_lunas'])
    ];

    // Upload logo baru jika ada
    if (!empty($_FILES['logo']['name'])) {
        $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $nama_file = 'logo_spam.' . $ext;
        $target = '../assets/uploads/logo/' . $nama_file;
        if (!is_dir('../assets/uploads/logo/')) {
            mkdir('../assets/uploads/logo/', 0755, true);
        }
        if (move_uploaded_file($_FILES['logo']['tmp_name'], $target)) {
            $new_settings['logo_url'] = 'assets/uploads/logo/' . $nama_file;
        }
    }

    if (file_put_contents($settings_file, json_encode($new_settings, JSON_PRETTY_PRINT))) {
        $success = "Pengaturan berhasil disimpan!";
        $settings = $new_settings;
    } else {
        $error = "Gagal menyimpan pengaturan. Pastikan folder memiliki izin tulis.";
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Pengaturan - SPAM</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body { background:#f4f7fe; font-family:'Segoe UI'; }
.bg-header{
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color:white; padding:18px;
    border-bottom-left-radius:20px; border-bottom-right-radius:20px;
}
.card-soft {
    background: white; border: none; border-radius: 20px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.05); padding: 20px; margin-bottom: 15px;
}
.section-title { font-size: 1rem; font-weight: 800; color: #354052; margin-bottom: 15px; }
.form-control, .form-select {
    border-radius: 12px; padding: 12px 15px; border: 1px solid #e0e0e0; background: #f8f9fa;
}
.form-control:focus, .form-select:focus {
    border-color: #3A7CA5; box-shadow: 0 0 0 0.25rem rgba(58, 124, 165, 0.25); background: white;
}
.form-label { font-weight: 700; font-size: 0.85rem; color: #4a5568; }
.btn-sage {
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color: white; border: none; border-radius: 12px; padding: 12px; font-weight: 700; width: 100%;
}
.logo-preview {
    width: 100px; height: 100px; border-radius: 16px; object-fit: cover;
    background: #f0f0f0; border: 2px dashed #3A7CA5;
}
.preview-box {
    background: #f8f9fa;
    border: 1px dashed #3A7CA5;
    border-radius: 12px;
    padding: 12px;
    font-family: monospace;
    font-size: 0.82rem;
    white-space: pre-wrap;
    color: #333;
    max-height: 200px;
    overflow-y: auto;
}
</style>
</head>
<body>

<div class="bg-header shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="dashboard.php" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Pengaturan</h5>
        <div style="width: 20px;"></div>
    </div>
</div>

<div class="container pb-5 mt-3">
    <?php if ($success): ?>
        <div class="alert alert-success" style="font-size:0.85rem; border-radius:10px;"><?= $success ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger" style="font-size:0.85rem; border-radius:10px;"><?= $error ?></div>
    <?php endif; ?>
    <?php if ($test_wa_result): ?>
        <?= $test_wa_result ?>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="simpan_pengaturan" value="1">

        <!-- Identitas SPAM -->
        <div class="card-soft">
            <div class="section-title"><i class="fa fa-building me-2 text-primary"></i>Identitas SPAM</div>
            <div class="text-center mb-3">
                <?php if (!empty($settings['logo_url'])): ?>
                    <img src="../<?= htmlspecialchars($settings['logo_url']) ?>" class="logo-preview mb-2">
                <?php else: ?>
                    <div class="logo-preview d-flex align-items-center justify-content-center mx-auto mb-2">
                        <i class="fa fa-droplet fa-2x text-muted"></i>
                    </div>
                <?php endif; ?>
                <input type="file" name="logo" class="form-control form-control-sm" accept="image/*">
                <small class="text-muted">Unggah logo baru (kosongkan jika tidak ingin mengganti)</small>
            </div>
            <div class="mb-3">
                <label class="form-label">Nama SPAM</label>
                <input type="text" name="nama_spam" class="form-control" value="<?= htmlspecialchars($settings['nama_spam']) ?>">
            </div>
            <div class="mb-3">
                <label class="form-label">Alamat</label>
                <textarea name="alamat_spam" class="form-control" rows="2"><?= htmlspecialchars($settings['alamat_spam']) ?></textarea>
            </div>
            <div class="mb-3">
                <label class="form-label">Nomor HP / WhatsApp</label>
                <input type="text" name="nomor_hp" class="form-control" value="<?= htmlspecialchars($settings['nomor_hp']) ?>" placeholder="08xxxxxxxxxx">
            </div>
        </div>

        <!-- Tampilan Website -->
        <div class="card-soft">
            <div class="section-title"><i class="fa fa-palette me-2 text-primary"></i>Tampilan Website</div>
            <div class="mb-3">
                <label class="form-label">Judul Hero (Halaman Utama)</label>
                <input type="text" name="judul_hero" class="form-control" value="<?= htmlspecialchars($settings['judul_hero']) ?>">
            </div>
            <div class="mb-3">
                <label class="form-label">Sub Judul Hero</label>
                <textarea name="subjudul_hero" class="form-control" rows="2"><?= htmlspecialchars($settings['subjudul_hero']) ?></textarea>
            </div>
            <div class="row g-2">
                <div class="col-6">
                    <label class="form-label">Warna Utama</label>
                    <div class="d-flex align-items-center">
                        <input type="color" name="warna_utama" class="form-control form-control-color" value="<?= htmlspecialchars($settings['warna_utama']) ?>">
                        <span class="ms-2 small text-muted"><?= htmlspecialchars($settings['warna_utama']) ?></span>
                    </div>
                </div>
                <div class="col-6">
                    <label class="form-label">Warna Gelap</label>
                    <div class="d-flex align-items-center">
                        <input type="color" name="warna_utama_gelap" class="form-control form-control-color" value="<?= htmlspecialchars($settings['warna_utama_gelap']) ?>">
                        <span class="ms-2 small text-muted"><?= htmlspecialchars($settings['warna_utama_gelap']) ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Integrasi WhatsApp (Fonnte) -->
        <div class="card-soft">
            <div class="section-title"><i class="fa fa-whatsapp me-2 text-success"></i>Integrasi WhatsApp (Fonnte)</div>
            <div class="alert alert-info small" style="border-radius:10px;">
                <i class="fa fa-info-circle me-1"></i> Daftar di <b>fonnte.com</b> untuk mendapatkan token gratis. Kosongkan jika belum punya.
            </div>
            <div class="mb-3">
                <label class="form-label">Token Fonnte</label>
                <input type="text" name="fonnte_token" class="form-control" value="<?= htmlspecialchars($settings['fonnte_token']) ?>" placeholder="Masukkan token dari Fonnte">
            </div>
            <div class="mb-3">
                <label class="form-label">Device ID (Opsional)</label>
                <input type="text" name="fonnte_device" class="form-control" value="<?= htmlspecialchars($settings['fonnte_device']) ?>" placeholder="Kosongkan untuk default">
            </div>

            <hr class="my-3">
            <div class="fw-bold small mb-2"><i class="fa fa-paper-plane me-1"></i> Test Kirim WhatsApp</div>
            <div class="row g-2 mb-2">
                <div class="col-7">
                    <input type="text" name="nomor_test" class="form-control form-control-sm" placeholder="08xxxxxxxxxx">
                </div>
                <div class="col-5">
                    <button type="submit" name="test_wa" class="btn btn-sm btn-success w-100" style="border-radius:10px;">
                        <i class="fa fa-paper-plane me-1"></i> Test Kirim
                    </button>
                </div>
            </div>
            <input type="hidden" name="fonnte_token" value="<?= htmlspecialchars($settings['fonnte_token']) ?>">
            <input type="hidden" name="pesan_test" value="Test pesan dari SPAM Tirtha Kedawung Desa Gemuruh.">
        </div>

        <!-- Format Pesan WhatsApp -->
        <div class="card-soft">
            <div class="section-title"><i class="fa fa-message me-2 text-primary"></i>Format Pesan WhatsApp</div>
            <div class="alert alert-warning small" style="border-radius:10px;">
                <i class="fa fa-lightbulb me-1"></i> <b>Variabel yang bisa digunakan:</b> 
                <code>{nama}</code>, <code>{bulan}</code>, <code>{tahun}</code>, <code>{pemakaian}</code>, <code>{abonemen}</code>, <code>{total}</code>
            </div>
            
            <div class="mb-3">
                <label class="form-label">Pesan Tagihan Terbit</label>
                <textarea name="format_pesan_tagihan" id="format_tagihan" class="form-control" rows="8"><?= htmlspecialchars($settings['format_pesan_tagihan']) ?></textarea>
                <small class="text-muted">Pesan yang dikirim saat petugas mencatat meteran dan tagihan terbit.</small>
            </div>
            <div class="mb-3">
                <label class="form-label">Preview Pesan Tagihan</label>
                <div class="preview-box" id="preview_tagihan"></div>
            </div>

            <hr class="my-3">

            <div class="mb-3">
                <label class="form-label">Pesan Pembayaran Lunas</label>
                <textarea name="format_pesan_lunas" id="format_lunas" class="form-control" rows="8"><?= htmlspecialchars($settings['format_pesan_lunas']) ?></textarea>
                <small class="text-muted">Pesan yang dikirim saat pelanggan melakukan pembayaran.</small>
            </div>
            <div class="mb-3">
                <label class="form-label">Preview Pesan Lunas</label>
                <div class="preview-box" id="preview_lunas"></div>
            </div>
        </div>

        <button type="submit" class="btn btn-sage mb-4">
            <i class="fa fa-save me-2"></i> Simpan Semua Pengaturan
        </button>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Preview pesan secara realtime
function updatePreview() {
    const formatTagihan = document.getElementById('format_tagihan').value;
    const formatLunas = document.getElementById('format_lunas').value;
    
    // Data dummy untuk preview
    const dummy = {
        '{nama}': 'Budi Santoso',
        '{bulan}': 'Juli',
        '{tahun}': '2026',
        '{pemakaian}': '12,500',
        '{abonemen}': 'Rp 10.000',
        '{total}': 'Rp 47.500'
    };
    
    let previewTagihan = formatTagihan;
    let previewLunas = formatLunas;
    
    for (const [key, value] of Object.entries(dummy)) {
        previewTagihan = previewTagihan.split(key).join(value);
        previewLunas = previewLunas.split(key).join(value);
    }
    
    document.getElementById('preview_tagihan').textContent = previewTagihan;
    document.getElementById('preview_lunas').textContent = previewLunas;
}

document.getElementById('format_tagihan').addEventListener('input', updatePreview);
document.getElementById('format_lunas').addEventListener('input', updatePreview);

// Jalankan preview saat halaman dimuat
updatePreview();
</script>
</body>
</html>