<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('settings_access');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_template') {
    $id = (int)$_POST['id'];
    $message = trim($_POST['message']);
    $type = $_POST['type'];
    $status = isset($_POST['status']) ? 1 : 0;

    if ($id) {
        $stmt = $pdo->prepare("UPDATE notification_templates SET message=?, type=?, status=? WHERE id=?");
        $stmt->execute([$message, $type, $status, $id]);
    } else {
        $name = trim($_POST['name']);
        $slug = trim($_POST['slug']);
        $stmt = $pdo->prepare("INSERT INTO notification_templates (name, slug, type, message, status) VALUES (?,?,?,?,?)");
        $stmt->execute([$name, $slug, $type, $message, $status]);
    }
    $_SESSION['success'] = 'Template saved.';
    header('Location: notification_settings.php'); exit;
}

$templates = $pdo->query("SELECT * FROM notification_templates ORDER BY template_name")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-bell me-2"></i>Notification Templates</h4>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>

        <div class="card">
            <div class="card-header d-flex justify-content-between">
                <span>Message Templates</span>
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#templateModal" onclick="resetTemplateForm()"><i class="fas fa-plus me-1"></i>Add Template</button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover no-datatable">
                        <thead><tr><th>Name</th><th>Slug</th><th>Type</th><th>Message</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($templates as $t): ?>
                            <tr>
                                <td><?= htmlspecialchars($t['name']) ?></td>
                                <td><code><?= htmlspecialchars($t['slug']) ?></code></td>
                                <td><span class="badge bg-<?= $t['type'] == 'SMS' ? 'primary' : ($t['type'] == 'WhatsApp' ? 'success' : 'info') ?>"><?= $t['type'] ?></span></td>
                                <td><small><?= htmlspecialchars(substr($t['message'], 0, 100)) ?>...</small></td>
                                <td><?= $t['status'] ? '<span class="badge badge-completed">Active</span>' : '<span class="badge badge-cancelled">Inactive</span>' ?></td>
                                <td>
                                    <button class="btn btn-sm btn-info" onclick="editTemplate(<?= htmlspecialchars(json_encode($t)) ?>)"><i class="fas fa-edit"></i></button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="templateModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <input type="hidden" name="action" value="save_template">
            <input type="hidden" name="id" id="tmplId" value="0">
            <div class="modal-header"><h5 class="modal-title" id="tmplModalTitle">Add Template</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Template Name</label>
                    <input type="text" name="name" id="tmplName" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Slug</label>
                    <input type="text" name="slug" id="tmplSlug" class="form-control" placeholder="e.g. repair_completed" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Type</label>
                    <select name="type" id="tmplType" class="form-select">
                        <option value="SMS">SMS</option>
                        <option value="WhatsApp">WhatsApp</option>
                        <option value="Email">Email</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Message Template</label>
                    <textarea name="message" id="tmplMessage" class="form-control" rows="4" required></textarea>
                    <small class="text-muted">Available placeholders: {customer_name}, {job_no}, {invoice_no}, {amount}, {shop_name}</small>
                </div>
                <div class="form-check">
                    <input type="checkbox" name="status" id="tmplStatus" class="form-check-input" checked>
                    <label class="form-check-label">Active</label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        </form>
    </div>
</div>

<script>
function resetTemplateForm() { $('#tmplId').val(0);$('#tmplModalTitle').text('Add Template');$('#tmplName,#tmplSlug,#tmplMessage').val('');$('#tmplType').val('SMS');$('#tmplStatus').prop('checked',true); }
function editTemplate(t) { $('#tmplId').val(t.id);$('#tmplModalTitle').text('Edit: '+t.name);$('#tmplName').val(t.name);$('#tmplSlug').val(t.slug);$('#tmplType').val(t.type);$('#tmplMessage').val(t.message);$('#tmplStatus').prop('checked',t.status==1);$('#templateModal').modal('show'); }
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
