<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';

requireRole('branch_admin');
$pageTitle = 'Kelola Template WhatsApp';

$db = db();

// ============================================================================
// 1. DETEKSI CABANG USER
// ============================================================================
$currentUserId = currentUserId();
$userBranchId = null;
$userBranchName = 'Unknown';

try {
    $stmt = $db->prepare("SELECT u.branch_id, b.name as branch_name 
                          FROM users u LEFT JOIN branches b ON u.branch_id = b.id 
                          WHERE u.id = ?");
    $stmt->execute([$currentUserId]);
    $row = $stmt->fetch();
    $userBranchId = $row ? (int)$row['branch_id'] : null;
    $userBranchName = $row['branch_name'] ?? 'Unknown';
} catch (\Throwable $e) {}

if (!$userBranchId) {
    redirect('/branch/dashboard.php', '❌ Akun Anda tidak terdaftar di cabang manapun.', 'error');
}

// ============================================================================
// 2. CEK TABEL wa_templates
// ============================================================================
$tableExists = false;
try {
    $check = $db->query("SHOW TABLES LIKE 'wa_templates'")->fetch();
    $tableExists = !empty($check);
} catch (\Throwable $e) {}

if (!$tableExists) {
    require __DIR__ . '/../includes/header.php';
    require __DIR__ . '/../includes/sidebar.php';
    echo '<div class="main-content"><div class="alert-modern danger" style="margin-top:20px;">
            <i class="bi bi-exclamation-triangle-fill"></i>
            <div><strong>Tabel wa_templates belum ada!</strong><br>
            Silakan jalankan query SQL berikut di phpMyAdmin untuk membuat tabel:<br>
            <code style="background:#fff;padding:5px;display:block;margin-top:5px;">
            CREATE TABLE `wa_templates` (`id` int(11) NOT NULL AUTO_INCREMENT, `branch_id` int(11) DEFAULT NULL, `title` varchar(100) NOT NULL, `slug` varchar(50) NOT NULL, `message` text NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`));
            </code></div></div></div>';
    require __DIR__ . '/../includes/footer.php';
    exit;
}

// ============================================================================
// 3. HANDLE ACTIONS (ADD, EDIT, DELETE)
// ============================================================================
$message = '';
$messageType = 'success';

// DELETE
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id']) && verifyCsrf($_GET['token'] ?? '')) {
    $id = (int)$_GET['id'];
    try {
        $stmt = $db->prepare("DELETE FROM wa_templates WHERE id = ? AND branch_id = ?");
        $stmt->execute([$id, $userBranchId]);
        logActivity($currentUserId, 'delete_template', "Hapus template WA ID: $id");
        redirect('/branch/templates.php', '✅ Template berhasil dihapus. Sistem akan kembali menggunakan pesan default.', 'success');
    } catch (\Throwable $e) {
        redirect('/branch/templates.php', '❌ Gagal menghapus: ' . $e->getMessage(), 'error');
    }
}

// ADD / EDIT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $id = (int)($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $slug = trim(strtolower(preg_replace('/[^a-z0-9_]/i', '_', $_POST['slug'] ?? '')));
    $msg = trim($_POST['message'] ?? '');

    if (empty($title) || empty($slug) || empty($msg)) {
        redirect('/branch/templates.php', '❌ Judul, Slug, dan Pesan wajib diisi!', 'error');
    }

    try {
        if ($id > 0) {
            // EDIT
            $stmt = $db->prepare("UPDATE wa_templates SET title = ?, slug = ?, message = ? WHERE id = ? AND branch_id = ?");
            $stmt->execute([$title, $slug, $msg, $id, $userBranchId]);
            logActivity($currentUserId, 'edit_template', "Edit template WA: $slug");
            redirect('/branch/templates.php', '✅ Template berhasil diperbarui!', 'success');
        } else {
            // ADD
            // Cek duplikasi slug di cabang ini
            $checkSlug = $db->prepare("SELECT id FROM wa_templates WHERE slug = ? AND branch_id = ?");
            $checkSlug->execute([$slug, $userBranchId]);
            if ($checkSlug->fetch()) {
                redirect('/branch/templates.php', "❌ Slug '<strong>$slug</strong>' sudah digunakan di cabang Anda. Gunakan slug lain.", 'error');
            }

            $stmt = $db->prepare("INSERT INTO wa_templates (branch_id, title, slug, message) VALUES (?, ?, ?, ?)");
            $stmt->execute([$userBranchId, $title, $slug, $msg]);
            logActivity($currentUserId, 'add_template', "Tambah template WA: $slug");
            redirect('/branch/templates.php', '✅ Template baru berhasil ditambahkan!', 'success');
        }
    } catch (\Throwable $e) {
        redirect('/branch/templates.php', '❌ Error database: ' . $e->getMessage(), 'error');
    }
}

// ============================================================================
// 4. FETCH DATA
// ============================================================================
$templates = [];
try {
    $stmt = $db->prepare("SELECT * FROM wa_templates WHERE branch_id = ? ORDER BY title ASC");
    $stmt->execute([$userBranchId]);
    $templates = $stmt->fetchAll();
} catch (\Throwable $e) {}

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>

<style>
/* Reusing styles from customers.php for consistency */
.navbar-modern { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); padding: 15px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 10px rgba(0,0,0,0.1); position: sticky; top: 0; z-index: 1000; }
.navbar-left { display: flex; align-items: center; gap: 15px; }
.burger-btn { background: rgba(255,255,255,0.15); border: none; color: white; width: 40px; height: 40px; border-radius: 10px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; }
.navbar-title { color: white; font-size: 1.2rem; font-weight: 700; margin: 0; }
.navbar-subtitle { color: rgba(255,255,255,0.85); font-size: 0.78rem; margin: 0; }
.main-content { padding: 20px; max-width: 1200px; margin: 0 auto; }
.page-header { margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.page-title { font-size: 1.6rem; font-weight: 700; color: #003D7A; margin: 0; display: flex; align-items: center; gap: 10px; }
.page-title i { font-size: 1.8rem; color: #0066CC; }
.btn-add { padding: 12px 24px; background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; border: none; border-radius: 12px; font-size: 0.95rem; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; box-shadow: 0 4px 15px rgba(0, 102, 204, 0.3); }
.btn-add:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 102, 204, 0.4); color: white; }
.card-modern { background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; }
.card-header-modern { color: white; padding: 16px 20px; font-size: 1rem; font-weight: 600; display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.card-header-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.card-header-modern .title-left { display: flex; align-items: center; gap: 10px; }
.card-body-modern { padding: 20px; }
.table-scroll { overflow-x: auto; }
.table-modern { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 0.88rem; min-width: 800px; }
.table-modern thead { background: #f8fafc; position: sticky; top: 0; z-index: 10; }
.table-modern th { padding: 12px 14px; text-align: left; font-weight: 700; color: #003D7A; border-bottom: 2px solid #e8f4f8; font-size: 0.78rem; text-transform: uppercase; }
.table-modern td { padding: 12px 14px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
.table-modern tbody tr:hover { background: #f8fafc; }
.badge-modern { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 20px; font-size: 0.72rem; font-weight: 700; }
.badge-modern.slug { background: #e3f2fd; color: #003D7A; font-family: monospace; font-size: 0.8rem; }
.msg-preview { font-size: 0.8rem; color: #555; max-width: 400px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block; }
.btn-action { width: 32px; height: 32px; border: none; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.3s ease; font-size: 0.88rem; text-decoration: none; margin-right: 4px; }
.btn-action.edit { background: #fff3cd; color: #856404; }
.btn-action.edit:hover { background: #FF9900; color: white; }
.btn-action.delete { background: #ffe5e5; color: #842029; }
.btn-action.delete:hover { background: #b02a37; color: white; }
.empty-state { text-align: center; padding: 50px 20px; }
.empty-state-icon { width: 70px; height: 70px; margin: 0 auto 16px; background: #f8fafc; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 2rem; color: #ccc; }

/* Modal */
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(4px); display: none; align-items: center; justify-content: center; z-index: 9999; }
.modal-content { background: white; border-radius: 16px; width: 90%; max-width: 650px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); overflow: hidden; max-height: 90vh; display: flex; flex-direction: column; }
.modal-header { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; padding: 16px 20px; display: flex; justify-content: space-between; align-items: center; }
.modal-header h3 { margin: 0; font-size: 1.1rem; display: flex; align-items: center; gap: 8px; font-weight: 700; }
.modal-close { background: rgba(255,255,255,0.2); border: none; color: white; font-size: 1.2rem; cursor: pointer; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; }
.modal-body { padding: 20px; overflow-y: auto; flex: 1; }
.modal-footer { padding: 16px 20px; background: #f8fafc; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #e8f4f8; }
.form-group { margin-bottom: 15px; }
.form-group label { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.85rem; }
.form-control { width: 100%; padding: 10px 14px; border: 2px solid #e8f4f8; border-radius: 10px; font-size: 0.9rem; font-family: inherit; box-sizing: border-box; }
.form-control:focus { outline: none; border-color: #0066CC; }
textarea.form-control { min-height: 150px; resize: vertical; }
.slug-quick-btns { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
.slug-quick-btn { padding: 4px 10px; background: #e3f2fd; color: #0066CC; border: 1px solid #bbdefb; border-radius: 6px; font-size: 0.75rem; font-weight: 600; cursor: pointer; }
.slug-quick-btn:hover { background: #0066CC; color: white; }
.btn-filter { padding: 10px 16px; border: none; border-radius: 10px; font-size: 0.88rem; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; }
.btn-filter.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; }
.btn-filter.outline { background: white; color: #666; border: 2px solid #e8f4f8; }
.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; font-size: 0.9rem; border: 2px solid; }
.alert-modern.success { background: #e8f5e9; border-color: #a5d6a7; color: #2e7d32; }
.alert-modern.danger { background: #ffebee; border-color: #ef9a9a; color: #c62828; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }
</style>

<div class="content-wrapper">
<div class="main-content">
    <!-- Navbar -->
    <div class="navbar-modern">
        <div class="navbar-left">
            <button class="burger-btn" onclick="toggleSidebar()"><i class="bi bi-list"></i></button>
            <div>
                <h1 class="navbar-title">Kelola Template WA</h1>
                <p class="navbar-subtitle"><i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?></p>
            </div>
        </div>
    </div>

    <div class="page-header">
        <h2 class="page-title"><i class="bi bi-lightning-charge-fill"></i> Template Pesan WhatsApp</h2>
        <button type="button" class="btn-add" onclick="openAddModal()">
            <i class="bi bi-plus-circle-fill"></i>
            <span>Tambah Template</span>
        </button>
    </div>

    <?= flashMessage() ?>

    <div class="alert-modern info">
        <i class="bi bi-info-circle-fill"></i>
        <div>
            <strong>Tips:</strong> Template yang Anda buat di sini akan otomatis menggantikan template default di halaman Broadcast. 
            Pastikan <strong>Slug</strong> ditulis dengan benar (misal: <code>reminder_h3</code>) agar Cron Job otomatis dapat memanggilnya.
        </div>
    </div>

    <!-- Table -->
    <div class="card-modern">
        <div class="card-header-modern primary">
            <div class="title-left">
                <i class="bi bi-collection"></i>
                <span>Daftar Template Cabang</span>
                <span class="badge-modern" style="background:rgba(255,255,255,0.2); color:white;"><?= count($templates) ?></span>
            </div>
        </div>
        <div class="card-body-modern" style="padding: 0;">
            <?php if (empty($templates)): ?>
                <div class="empty-state">
                    <div class="empty-state-icon"><i class="bi bi-inbox"></i></div>
                    <h5 style="color:#666; font-weight:600;">Belum ada template khusus</h5>
                    <p style="color:#999; font-size:0.85rem;">Cabang Anda masih menggunakan template default sistem. Klik "Tambah Template" untuk membuat yang baru.</p>
                </div>
            <?php else: ?>
                <div class="table-scroll">
                    <table class="table-modern">
                        <thead>
                            <tr>
                                <th>Judul Template</th>
                                <th>Slug (Kode Cron)</th>
                                <th>Preview Pesan</th>
                                <th style="width: 100px; text-align: center;">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($templates as $tpl): ?>
                                <tr>
                                    <td><strong style="color:#003D7A;"><?= htmlspecialchars($tpl['title']) ?></strong></td>
                                    <td><span class="badge-modern slug"><?= htmlspecialchars($tpl['slug']) ?></span></td>
                                    <td><span class="msg-preview"><?= htmlspecialchars(nl2br($tpl['message'])) ?></span></td>
                                    <td style="text-align: center;">
                                        <button type="button" class="btn-action edit" 
                                            onclick="openEditModal(<?= $tpl['id'] ?>, '<?= htmlspecialchars(addslashes($tpl['title']), ENT_QUOTES) ?>', '<?= htmlspecialchars(addslashes($tpl['slug']), ENT_QUOTES) ?>', `<?= htmlspecialchars(addslashes($tpl['message']), ENT_QUOTES) ?>`)" 
                                            title="Edit">
                                            <i class="bi bi-pencil-fill"></i>
                                        </button>
                                        <a href="/branch/templates.php?action=delete&id=<?= $tpl['id'] ?>&token=<?= csrfToken() ?>" 
                                           class="btn-action delete" 
                                           onclick="return confirm('Yakin hapus template ini? Sistem akan kembali menggunakan pesan default.')" 
                                           title="Hapus">
                                            <i class="bi bi-trash-fill"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
</div>

<!-- MODAL FORM -->
<div id="templateModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header">
            <h3><i class="bi bi-chat-left-text-fill"></i> <span id="modalTitle">Tambah Template</span></h3>
            <button class="modal-close" onclick="closeModal()">&times;</button>
        </div>
        <form method="POST" id="templateForm">
            <?= csrfField() ?>
            <input type="hidden" name="id" id="tpl_id" value="0">
            <div class="modal-body">
                <div class="form-group">
                    <label><i class="bi bi-tag-fill"></i> Judul Template <span style="color:red;">*</span></label>
                    <input type="text" name="title" id="tpl_title" class="form-control" placeholder="Contoh: Reminder Jatuh Tempo H-3" required>
                </div>
                <div class="form-group">
                    <label><i class="bi bi-hash"></i> Slug / Kode Unik <span style="color:red;">*</span></label>
                    <input type="text" name="slug" id="tpl_slug" class="form-control" placeholder="Contoh: reminder_h3" required pattern="[a-zA-Z0-9_]+">
                    <small style="color:#666; font-size:0.75rem;">Hanya huruf kecil, angka, dan underscore. Ini yang akan dipanggil oleh Cron Job.</small>
                    <div class="slug-quick-btns">
                        <span style="font-size:0.75rem; color:#666; align-self:center;">Quick Insert:</span>
                        <button type="button" class="slug-quick-btn" onclick="insertSlug('reminder_h3', 'Reminder H-3')">H-3</button>
                        <button type="button" class="slug-quick-btn" onclick="insertSlug('reminder_h1', 'Reminder H-1')">H-1</button>
                        <button type="button" class="slug-quick-btn" onclick="insertSlug('reminder_due', 'Jatuh Tempo Hari H')">Hari H</button>
                        <button type="button" class="slug-quick-btn" onclick="insertSlug('payment_success', 'Konfirmasi Sukses Bayar')">Sukses Bayar</button>
                    </div>
                </div>
                <div class="form-group">
                    <label><i class="bi bi-chat-left-text"></i> Isi Pesan <span style="color:red;">*</span></label>
                    <textarea name="message" id="tpl_message" class="form-control" placeholder="Ketik pesan template di sini..." required></textarea>
                    <small style="color:#666; font-size:0.75rem;">
                        Gunakan placeholder: <code>[customer_number]</code>, <code>[nama]</code>, <code>[paket]</code>, <code>[Link Pembayaran]</code>
                    </small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-filter outline" onclick="closeModal()">Batal</button>
                <button type="submit" class="btn-filter primary">
                    <i class="bi bi-save-fill"></i> Simpan Template
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}

function openAddModal() {
    document.getElementById('modalTitle').innerText = 'Tambah Template Baru';
    document.getElementById('templateForm').action = '/branch/templates.php';
    document.getElementById('tpl_id').value = '0';
    document.getElementById('tpl_title').value = '';
    document.getElementById('tpl_slug').value = '';
    document.getElementById('tpl_message').value = '';
    document.getElementById('templateModal').style.display = 'flex';
}

function openEditModal(id, title, slug, message) {
    document.getElementById('modalTitle').innerText = 'Edit Template';
    document.getElementById('templateForm').action = '/branch/templates.php';
    document.getElementById('tpl_id').value = id;
    document.getElementById('tpl_title').value = title;
    document.getElementById('tpl_slug').value = slug;
    // Unescape backticks and slashes for textarea
    document.getElementById('tpl_message').value = message.replace(/\\`/g, '`').replace(/\\\\/g, '\\');
    document.getElementById('templateModal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('templateModal').style.display = 'none';
}

function insertSlug(slug, title) {
    document.getElementById('tpl_slug').value = slug;
    document.getElementById('tpl_title').value = title;
    document.getElementById('tpl_slug').focus();
}

// Close modal on outside click
window.onclick = function(event) {
    const modal = document.getElementById('templateModal');
    if (event.target === modal) closeModal();
}
</script>

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