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

<?php
if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ADMIN_NO_PERMISSION'] ?? 'You do not have permission to access this page', 'danger');
    redirectTo(getCleanUrl('index'));
}

// Handle CRUD operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.', 'danger');
        redirectTo('admin/snippets');
        exit;
    }

    // Create snippet
    if (isset($_POST['create_snippet'])) {
        $subject = sanitizeInput($_POST['subject']);
        $category = sanitizeInput($_POST['category']);
        $content = sanitizeInput($_POST['content']);

        if (empty($subject) || empty($category) || empty($content)) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SNIPPETS_ALL_FIELDS_REQUIRED'] ?? 'All fields are required.', 'danger');
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO ticket_snippets (subject, category, content, created_by) VALUES (?, ?, ?, ?)");
                $stmt->execute([$subject, $category, $content, $_SESSION['user_id']]);
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SNIPPET_CREATED_SUCCESS'] ?? 'Snippet created successfully.', 'success');
                redirectTo('admin/snippets');
                exit;
            } catch (PDOException $e) {
                $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_SNIPPET_CREATE_ERROR'] ?? 'Error creating snippet: %s', $e->getMessage()), 'danger');
            }
        }
    }

    // Update snippet
    if (isset($_POST['update_snippet'])) {
        $id = (int)$_POST['snippet_id'];
        $subject = sanitizeInput($_POST['subject']);
        $category = sanitizeInput($_POST['category']);
        $content = sanitizeInput($_POST['content']);

        if (empty($subject) || empty($category) || empty($content)) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SNIPPETS_ALL_FIELDS_REQUIRED'] ?? 'All fields are required.', 'danger');
        } else {
            try {
                $stmt = $pdo->prepare("UPDATE ticket_snippets SET subject = ?, category = ?, content = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$subject, $category, $content, $id]);
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SNIPPET_UPDATED_SUCCESS'] ?? 'Snippet updated successfully.', 'success');
                redirectTo('admin/snippets');
                exit;
            } catch (PDOException $e) {
                $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_SNIPPET_UPDATE_ERROR'] ?? 'Error updating snippet: %s', $e->getMessage()), 'danger');
            }
        }
    }

    // Delete snippet
    if (isset($_POST['delete_snippet'])) {
        $id = (int)$_POST['snippet_id'];
        try {
            $stmt = $pdo->prepare("DELETE FROM ticket_snippets WHERE id = ?");
            $stmt->execute([$id]);
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SNIPPET_DELETED_SUCCESS'] ?? 'Snippet deleted successfully.', 'success');
            redirectTo('admin/snippets');
            exit;
        } catch (PDOException $e) {
            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_SNIPPET_DELETE_ERROR'] ?? 'Error deleting snippet: %s', $e->getMessage()), 'danger');
        }
    }
}

// Get all snippets
$stmt = $pdo->prepare("SELECT s.*, u.name as created_by_name FROM ticket_snippets s LEFT JOIN users u ON s.created_by = u.id ORDER BY s.category, s.subject");
$stmt->execute();
$snippets = $stmt->fetchAll();

// Get distinct categories for filter
$stmt = $pdo->prepare("SELECT DISTINCT category FROM ticket_snippets ORDER BY category");
$stmt->execute();
$categories = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h4><?php echo $lang_admin['ADMIN_SNIPPETS_PAGE_TITLE'] ?? 'Ticket Snippets Management'; ?></h4>
    <div>
        <button type="button" class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#createSnippetModal">
            <i class="bi bi-plus-circle"></i> <?php echo $lang_admin['ADMIN_SNIPPETS_BTN_ADD_NEW'] ?? 'Add New Snippet'; ?>
        </button>
        <a href="<?php echo getCleanUrl('admin/dashboard'); ?>" class="btn btn-outline-primary">
            <i class="bi bi-arrow-left"></i> <?php echo $lang_admin['ADMIN_SETTINGS_BTN_BACK_TO_DASHBOARD'] ?? 'Back to Dashboard'; ?>
        </a>
    </div>
</div>

<div class="row mb-4">
    <div class="col-md-6">
        <div class="input-group">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" class="form-control" id="searchSnippets" placeholder="<?php echo $lang_admin['ADMIN_SNIPPETS_SEARCH_PLACEHOLDER'] ?? 'Search snippets...'; ?>">
        </div>
    </div>
    <div class="col-md-6">
        <select class="form-select" id="categoryFilter">
            <option value=""><?php echo $lang_admin['ADMIN_SNIPPETS_FILTER_ALL_CATEGORIES'] ?? 'All Categories'; ?></option>
            <?php foreach ($categories as $cat): ?>
                <option value="<?php echo htmlspecialchars($cat['category']); ?>"><?php echo htmlspecialchars($cat['category']); ?></option>
            <?php endforeach; ?>
        </select>
    </div>
</div>

<div class="card">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0"><?php echo $lang_admin['ADMIN_SNIPPETS_CARD_HEADER'] ?? 'Ticket Snippets'; ?></h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-striped table-hover mb-0">
                <thead class="table-dark">
                    <tr>
                        <th><?php echo $lang_admin['ADMIN_SNIPPETS_TH_SUBJECT'] ?? 'Subject'; ?></th>
                        <th><?php echo $lang_admin['ADMIN_SNIPPETS_TH_CATEGORY'] ?? 'Category'; ?></th>
                        <th><?php echo $lang_admin['ADMIN_SNIPPETS_TH_CONTENT_PREVIEW'] ?? 'Content Preview'; ?></th>
                        <th><?php echo $lang_admin['ADMIN_SNIPPETS_TH_CREATED_BY'] ?? 'Created By'; ?></th>
                        <th><?php echo $lang_admin['ADMIN_SNIPPETS_TH_CREATED_AT'] ?? 'Created'; ?></th>
                        <th><?php echo $lang_admin['ADMIN_USERS_TH_ACTIONS'] ?? 'Actions'; ?></th>
                    </tr>
                </thead>
                <tbody id="snippetsTableBody">
                    <?php if (empty($snippets)): ?>
                        <tr>
                            <td colspan="6" class="text-center py-4">
                                <div class="text-muted">
                                    <i class="bi bi-inbox-fill mb-2" style="font-size: 2rem;"></i>
                                    <p><?php echo $lang_admin['ADMIN_SNIPPETS_NO_SNIPPETS_TEXT'] ?? 'No snippets found. Create your first snippet to get started.'; ?></p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($snippets as $snippet): ?>
                            <tr data-category="<?php echo $snippet['category']; ?>" data-subject="<?php echo $snippet['subject']; ?>" data-content="<?php echo $snippet['content']; ?>">
                                <td>
                                    <strong><?php echo $snippet['subject']; ?></strong>
                                </td>
                                <td>
                                    <span class="badge bg-info"><?php echo $snippet['category']; ?></span>
                                </td>
                                <td>
                                    <?php echo substr($snippet['content'], 0, 100) . (strlen($snippet['content']) > 100 ? '...' : ''); ?>
                                </td>
                                <td><?php echo $snippet['created_by_name']; ?></td>
                                <td><?php echo getFormattedDate($snippet['created_at'], DATETIME_FORMAT); ?></td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="editSnippet(<?php echo $snippet['id']; ?>)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteSnippet(<?php echo $snippet['id']; ?>)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Create Snippet Modal -->
<div class="modal fade" id="createSnippetModal" tabindex="-1" aria-labelledby="createSnippetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createSnippetModalLabel"><?php echo $lang_admin['ADMIN_SNIPPETS_MODAL_CREATE_TITLE'] ?? 'Create New Snippet'; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
            </div>
            <form method="post">
                <?php echo get_csrf_input_field(); ?>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="subject" class="form-label"><?php echo $lang_admin['ADMIN_SNIPPETS_LBL_SUBJECT'] ?? 'Subject'; ?></label>
                        <input type="text" class="form-control" id="subject" name="subject" required>
                    </div>
                    <div class="mb-3">
                        <label for="category" class="form-label"><?php echo $lang_admin['ADMIN_SNIPPETS_LBL_CATEGORY'] ?? 'Category'; ?></label>
                        <input type="text" class="form-control" id="category" name="category" required placeholder="<?php echo $lang_admin['ADMIN_SNIPPETS_PLACEHOLDER_CATEGORY'] ?? 'e.g., Technical Support, Billing, General'; ?>">
                    </div>
                    <div class="mb-3">
                        <label for="content" class="form-label"><?php echo $lang_admin['ADMIN_SNIPPETS_LBL_CONTENT'] ?? 'Content'; ?></label>
                        <textarea class="form-control" id="content" name="content" rows="8" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                    <button type="submit" name="create_snippet" class="btn btn-primary"><?php echo $lang_admin['ADMIN_SNIPPETS_BTN_CREATE_MODAL'] ?? 'Create Snippet'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Snippet Modal -->
<div class="modal fade" id="editSnippetModal" tabindex="-1" aria-labelledby="editSnippetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editSnippetModalLabel"><?php echo $lang_admin['ADMIN_SNIPPETS_MODAL_EDIT_TITLE'] ?? 'Edit Snippet'; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
            </div>
            <form method="post">
                <?php echo get_csrf_input_field(); ?>
                <input type="hidden" id="edit_snippet_id" name="snippet_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="edit_subject" class="form-label"><?php echo $lang_admin['ADMIN_SNIPPETS_LBL_SUBJECT'] ?? 'Subject'; ?></label>
                        <input type="text" class="form-control" id="edit_subject" name="subject" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_category" class="form-label"><?php echo $lang_admin['ADMIN_SNIPPETS_LBL_CATEGORY'] ?? 'Category'; ?></label>
                        <input type="text" class="form-control" id="edit_category" name="category" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_content" class="form-label"><?php echo $lang_admin['ADMIN_SNIPPETS_LBL_CONTENT'] ?? 'Content'; ?></label>
                        <textarea class="form-control" id="edit_content" name="content" rows="8" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                    <button type="submit" name="update_snippet" class="btn btn-primary"><?php echo $lang_admin['ADMIN_SNIPPETS_BTN_UPDATE_MODAL'] ?? 'Update Snippet'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Snippet Modal -->
<div class="modal fade" id="deleteSnippetModal" tabindex="-1" aria-labelledby="deleteSnippetModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteSnippetModalLabel"><?php echo $lang_admin['ADMIN_SNIPPETS_MODAL_DELETE_TITLE'] ?? 'Delete Snippet'; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
            </div>
            <form method="post">
                <?php echo get_csrf_input_field(); ?>
                <input type="hidden" id="delete_snippet_id" name="snippet_id">
                <div class="modal-body">
                    <p><?php echo $lang_admin['ADMIN_SNIPPETS_CONFIRM_DELETE_TEXT'] ?? 'Are you sure you want to delete this snippet?'; ?></p>
                    <p><strong><?php echo $lang_admin['ADMIN_SNIPPETS_LBL_SUBJECT_CONFIRM'] ?? 'Subject:'; ?></strong> <span id="delete_snippet_subject"></span></p>
                    <p class="text-danger"><?php echo $lang_admin['ADMIN_PRODUCTS_TEXT_ACTION_CANNOT_BE_UNDONE'] ?? 'This action cannot be undone.'; ?></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                    <button type="submit" name="delete_snippet" class="btn btn-danger"><?php echo $lang_admin['ADMIN_SNIPPETS_BTN_DELETE_CONFIRM_MODAL'] ?? 'Delete Snippet'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
// Store snippet data for JavaScript access  
const snippetsData = <?php echo json_encode($snippets); ?>;

// Wait for Bootstrap to be available
function waitForBootstrap(callback, attempts = 0) {
    if (typeof bootstrap !== 'undefined') {
        callback();
    } else if (attempts < 50) { // Try for 5 seconds
        setTimeout(() => waitForBootstrap(callback, attempts + 1), 100);
    } else {
        console.error('Bootstrap failed to load after 5 seconds');
    }
}

// Initialize everything after Bootstrap is ready
waitForBootstrap(function() {
    
    // Search and filter functionality
    const searchInput = document.getElementById('searchSnippets');
    const categoryFilter = document.getElementById('categoryFilter');
    
    if (searchInput) searchInput.addEventListener('input', filterSnippets);
    if (categoryFilter) categoryFilter.addEventListener('change', filterSnippets);

    function filterSnippets() {
        const searchTerm = searchInput.value.toLowerCase();
        const categoryFilterValue = categoryFilter.value;
        const rows = document.querySelectorAll('#snippetsTableBody tr');
        
        rows.forEach(row => {
            if (row.cells.length === 1) return; // Skip empty state row
            
            const subject = row.dataset.subject ? row.dataset.subject.toLowerCase() : '';
            const category = row.dataset.category || '';
            const content = row.dataset.content ? row.dataset.content.toLowerCase() : '';
            
            const matchesSearch = subject.includes(searchTerm) || content.includes(searchTerm);
            const matchesCategory = categoryFilterValue === '' || category === categoryFilterValue;
            
            row.style.display = (matchesSearch && matchesCategory) ? '' : 'none';
        });
    }

    // Global functions for buttons
    window.editSnippet = function(id) {
        const snippet = snippetsData.find(s => s.id == id);
        if (snippet) {
            document.getElementById('edit_snippet_id').value = snippet.id;
            document.getElementById('edit_subject').value = snippet.subject;
            document.getElementById('edit_category').value = snippet.category;
            // Convert \n to actual newlines for textarea display
            const content = snippet.content.replace(/\\n/g, '\n');
            document.getElementById('edit_content').value = content;
            
            const modal = new bootstrap.Modal(document.getElementById('editSnippetModal'));
            modal.show();
        } else {
            console.error('Snippet not found:', id);
        }
    };

    window.deleteSnippet = function(id) {
        const snippet = snippetsData.find(s => s.id == id);
        if (snippet) {
            document.getElementById('delete_snippet_id').value = snippet.id;
            document.getElementById('delete_snippet_subject').textContent = snippet.subject;
            
            const modal = new bootstrap.Modal(document.getElementById('deleteSnippetModal'));
            modal.show();
        } else {
            console.error('Snippet not found for delete:', id);
        }
    };
    
    // Let Bootstrap handle the create button automatically via data-bs-toggle
});
</script> 