<?php
require_once '../../config.php';
require_once '../../functions.php';

check_admin_auth();

$message = '';
$error = '';
$templates = [];

// Handle Create Template
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_template'])) {
    $title = $_POST['title'] ?? '';
    $msg_body = $_POST['message'] ?? '';
    $owner_type = $_POST['owner_type'] ?? 'admin';
    $owner_id = ($owner_type === 'user') ? ($_POST['target_user_id'] ?? null) : null;

    if ($title && $msg_body) {
        try {
            $stmt = $pdo->prepare("INSERT INTO sms_templates (title, message, owner_type, owner_id) VALUES (?, ?, ?, ?)");
            if ($stmt->execute([$title, $msg_body, $owner_type, $owner_id])) {
                $message = "Template created!";
            } else {
                $error = "Failed to create template.";
            }
        } catch (PDOException $e) {
            $error = $e->getMessage();
        }
    } else {
        $error = "Required fields missing.";
    }
}

// Handle Edit Template
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_template'])) {
    $id = $_POST['template_id'];
    $title = $_POST['title'];
    $message_body = $_POST['message'];
    try {
        $stmt = $pdo->prepare("UPDATE sms_templates SET title = ?, message = ? WHERE id = ?");
        if ($stmt->execute([$title, $message_body, $id])) {
            $message = "Template updated.";
        } else {
            $error = "Failed to update.";
        }
    } catch (PDOException $e) {
        $error = $e->getMessage();
    }
}

// Handle Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_template'])) {
    $id = $_POST['template_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM sms_templates WHERE id = ?");
        if ($stmt->execute([$id])) {
            $message = "Template deleted.";
        }
    } catch (PDOException $e) {
        $error = $e->getMessage();
    }
}

// Handle Toggle Status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_status'])) {
    $id = $_POST['template_id'];
    $new = ($_POST['current_status'] === 'active') ? 'inactive' : 'active';
    try {
        $stmt = $pdo->prepare("UPDATE sms_templates SET status = ? WHERE id = ?");
        $stmt->execute([$new, $id]);
        $message = "Status updated.";
    } catch (PDOException $e) {
        $error = $e->getMessage();
    }
}

// Fetch templates
try {
    $stmt = $pdo->query("SELECT t.*, u.username as user_name FROM sms_templates t LEFT JOIN users u ON t.owner_type = 'user' AND t.owner_id = u.id ORDER BY t.id DESC");
    if ($stmt)
        $templates = $stmt->fetchAll() ?: [];
} catch (PDOException $e) {
    // Fallback without join
    try {
        $stmt = $pdo->query("SELECT * FROM sms_templates ORDER BY id DESC");
        $templates = $stmt->fetchAll() ?: [];
    } catch (PDOException $e2) {
    }
}

// Fetch users for assignment
$users = [];
try {
    $stmt = $pdo->query("SELECT id, username FROM users WHERE status='active' ORDER BY username");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) {
}

$pageTitle = "Templates - SMS Admin";
include '../includes/header.php';
include '../includes/sidebar.php';
include '../includes/navbar.php';
?>

<div class="page-header">
    <h1 class="page-title">📋 Templates</h1>
    <div>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">Templates</li>
        </ol>
    </div>
</div>

<?php if ($message): ?>
    <div class="alert alert-success alert-dismissible fade show"><?php echo htmlspecialchars($message); ?><button
            class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show"><?php echo htmlspecialchars($error); ?><button
            class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="row">
    <!-- Create Template -->
    <div class="col-xl-4 fade-in-up">
        <div class="card mb-4">
            <div class="card-header d-flex align-items-center">
                <h3 class="card-title mb-0">Add Template</h3>
                <span class="ai-badge ms-auto">NEW</span>
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Title</label>
                        <input type="text" name="title" class="form-control" required placeholder="e.g. Eid Greeting">
                    </div>
                    <div class="mb-3">
                        <label class="form-label d-flex align-items-center">
                            Message Body
                            <button type="button" class="btn btn-ai-generate btn-sm ms-auto" id="aiGenBtn">
                                <i class="fe fe-zap"></i> AI Generate
                            </button>
                        </label>
                        <textarea name="message" class="form-control" rows="5" required id="createMsgBody"
                            placeholder="Type or use AI to generate..."></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Visibility</label>
                        <select name="owner_type" class="form-select" id="ownerTypeSelect">
                            <option value="admin">🌐 Global (All Users)</option>
                            <option value="user">👤 Specific User</option>
                        </select>
                    </div>
                    <div class="mb-3" id="userSelectDiv" style="display:none;">
                        <label class="form-label">Assign To User</label>
                        <select name="target_user_id" class="form-select">
                            <option value="">-- Select User --</option>
                            <?php foreach ($users as $u): ?>
                                <option value="<?php echo $u['id']; ?>"><?php echo htmlspecialchars($u['username']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <button type="submit" name="create_template" class="btn btn-modern-primary w-100">
                        <i class="fe fe-save me-2"></i>Save Template
                    </button>
                </form>

                <!-- AI Generate Panel -->
                <div class="ai-panel mt-3" id="aiPanel" style="display:none;">
                    <div class="ai-header"><i class="fe fe-cpu"></i> AI Template Generator</div>
                    <div class="mb-2">
                        <input type="text" id="aiPromptInput" class="form-control"
                            placeholder="What should the SMS be about?">
                    </div>
                    <div class="row mb-2">
                        <div class="col-6">
                            <select id="aiLang" class="form-select form-select-sm">
                                <option value="English">English</option>
                                <option value="Bengali">Bengali</option>
                                <option value="Banglish">Banglish</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <select id="aiLimit" class="form-select form-select-sm">
                                <option value="160">160 chars</option>
                                <option value="320">320 chars</option>
                            </select>
                        </div>
                    </div>
                    <button type="button" id="aiDoGenerate" class="btn btn-ai-generate btn-sm w-100">
                        <i class="fe fe-zap"></i> Generate
                    </button>
                    <div class="ai-preview-box mt-2" id="aiPreview" style="display:none;"></div>
                    <button type="button" id="aiUseBtn" class="btn btn-modern-success btn-sm w-100 mt-2"
                        style="display:none;">Use This Text</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Template List -->
    <div class="col-xl-8 fade-in-up">
        <div class="card mb-4">
            <div class="card-header d-flex align-items-center">
                <h3 class="card-title mb-0">Saved Templates</h3>
                <small class="ms-auto text-muted"><?php echo count($templates); ?> templates</small>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th>Message</th>
                                <th>Owner</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                                <?php if (!empty($templates)): ?>
                                    <?php foreach ($templates as $t): ?>
                                    <tr>
                                        <td class="fw-bold"><?php echo htmlspecialchars($t['title']); ?></td>
                                        <td><small><?php echo htmlspecialchars(substr($t['message'], 0, 60)); ?>...</small></td>
                                        <td>
                                                <?php if (($t['owner_type'] ?? 'admin') === 'admin'): ?>
                                                <span class="badge-global">🌐 Global</span>
                                                <?php else: ?>
                                                <span class="badge-user">👤
                                                    <?php echo htmlspecialchars($t['user_name'] ?? 'User #' . $t['owner_id']); ?></span>
                                                <?php endif; ?>
                                        </td>
                                        <td>
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="toggle_status" value="1">
                                                <input type="hidden" name="template_id" value="<?php echo $t['id']; ?>">
                                                <input type="hidden" name="current_status"
                                                    value="<?php echo $t['status'] ?? 'active'; ?>">
                                                <button type="submit"
                                                    class="btn btn-sm btn-<?php echo ($t['status'] ?? 'active') === 'active' ? 'success' : 'secondary'; ?>">
                                                        <?php echo ucfirst($t['status'] ?? 'active'); ?>
                                                </button>
                                            </form>
                                        </td>
                                        <td>
                                            <a href="javascript:void(0)" class="btn btn-primary btn-sm me-1 edit-template-btn"
                                                data-id="<?php echo $t['id']; ?>"
                                                data-title="<?php echo htmlspecialchars($t['title']); ?>"
                                                data-message="<?php echo htmlspecialchars($t['message']); ?>">
                                                <i class="fa fa-edit"></i>
                                            </a>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Delete?');">
                                                <input type="hidden" name="delete_template" value="1">
                                                <input type="hidden" name="template_id" value="<?php echo $t['id']; ?>">
                                                <button type="submit" class="btn btn-danger btn-sm"><i
                                                        class="fa fa-trash"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center text-muted">No templates yet. Create one or use AI!
                                    </td>
                                </tr>
                                <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editTemplateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Template</h5><button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" id="editTemplateForm">
                    <input type="hidden" name="template_id" id="edit_template_id">
                    <input type="hidden" name="edit_template" value="1">
                    <div class="mb-3">
                        <label class="form-label">Title</label>
                        <input type="text" name="title" class="form-control" id="edit_title" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Message</label>
                        <textarea name="message" class="form-control" rows="5" id="edit_message" required></textarea>
                    </div>
                    <button type="submit" class="btn btn-modern-primary w-100">Update Template</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php
$extra_scripts = '
<script>
$(document).ready(function() {
    // Edit modal
    $(".edit-template-btn").on("click", function() {
        $("#edit_template_id").val($(this).data("id"));
        $("#edit_title").val($(this).data("title"));
        $("#edit_message").val($(this).data("message"));
        $("#editTemplateModal").modal("show");
    });

    // Owner type toggle
    $("#ownerTypeSelect").change(function() {
        $("#userSelectDiv").toggle($(this).val() === "user");
    });

    // AI Generate panel toggle
    $("#aiGenBtn").click(function() { $("#aiPanel").slideToggle(); });

    // AI Generate action
    $("#aiDoGenerate").click(function() {
        var prompt = $("#aiPromptInput").val();
        if (!prompt) { alert("Enter a topic!"); return; }
        var btn = $(this);
        btn.html("<i class=\"fe fe-loader spin\"></i> Generating...").prop("disabled", true);
        
        $.post("' . base_url('public/api/ai_generate.php') . '", {
            action: "generate", prompt: prompt, language: $("#aiLang").val(), char_limit: $("#aiLimit").val()
        }, function(r) {
            if (r.success) {
                $("#aiPreview").html(r.text).show();
                $("#aiUseBtn").show().data("text", r.text);
            } else {
                $("#aiPreview").html("<span class=\"text-danger\">" + r.error + "</span>").show();
            }
            btn.html("<i class=\"fe fe-zap\"></i> Generate").prop("disabled", false);
        }, "json").fail(function() {
            btn.html("<i class=\"fe fe-zap\"></i> Generate").prop("disabled", false);
        });
    });

    // Use AI text
    $("#aiUseBtn").click(function() {
        $("#createMsgBody").val($(this).data("text"));
        $("#aiPanel").slideUp();
    });
});
</script>
<style>.spin{animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}</style>
';
include '../includes/footer.php';
?>