<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("user_header.php");
require_once '../src/InternalTicket.php';
$projectsType = InternalTicket::getEternalProjects($BitrixUser);

?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/themes/material_green.css">
<link href="../vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet" />

<style>
    body {
        background-color: #f5f8fa;
    }

    .card {
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        max-width: 900px;
        margin: 0 auto;
    }

    .btn-primary {
        background-color: #0d6efd;
        border-color: #0d6efd;
    }

    .btn-primary:hover {
        background-color: #0b5ed7;
    }

    .styled-table {
        width: 100% !important;
        border-collapse: collapse;
        font-size: 0.9em;
        min-width: 100%;
        border-radius: 5px;
        overflow-x: auto;
    }

    .styled-table thead tr {
        background-color: #009879 !important;
        color: #ffffff;
        font-weight: bold;
    }

    .styled-table th,
    .styled-table td {
        padding: 12px 15px;
        text-align: left;
        vertical-align: middle;
    }

    .styled-table tbody tr {
        border-bottom: 1px solid #dddddd;
    }

    .styled-table tbody tr:nth-of-type(even) {
        background-color: #956fff;
    }

    .styled-table tbody tr:last-of-type {
        border-bottom: 2px solid #009879;
    }

    .styled-table tbody tr:hover {
        background-color: #009879;
        color: #fff;
        font-weight: bold;
    }

    .page-item.active .page-link {
        background-color: #009879 !important;
        color: #fff;
        border: none !important;
    }

    .flatpickr-input {
        background-color: white !important;
        cursor: pointer;
    }

    .form-label {
        font-weight: 600;
    }

    .filter-icon {
        float: right;
        color: white;
        cursor: pointer;
        font-size: 1.1em;
        user-select: none;
        position: relative;
    }

    .filter-dropdown {
        display: none;
        position: absolute;
        background: white;
        border: 1px solid #ddd;
        padding: 6px;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
        z-index: 9999;
        max-height: 250px;
        overflow-y: auto;
        width: 220px;
        top: 100%;
        left: 0;
        margin-top: 4px;
        border-radius: 4px;
        color: #000;
    }

    .filter-dropdown label {
        display: block;
        margin-bottom: 4px;
        cursor: pointer;
        font-size: 0.9em;
    }

    .filter-dropdown button {
        margin-top: 5px;
        background-color: #009879;
        color: white;
        border: none;
        padding: 6px 10px;
        border-radius: 4px;
        width: 100%;
        cursor: pointer;
        font-weight: bold;
    }

    .filter-dropdown input[type="search"] {
        width: 100%;
        padding: 4px 6px;
        margin-bottom: 8px;
        border: 1px solid #ccc;
        border-radius: 3px;
    }
</style>

<div class="container-fluid my-1">


    <?php if (!empty($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($_SESSION['success_message']) ?>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>

    <?php if (!empty($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($_SESSION['error_message']) ?>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>


    <h4 class="text-center mb-4">Create New Ticket</h4>

    <div class="card p-4">
        <form action="../src/ExternalTicket.php" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="bitrix24_user_id" value="<?= $BitrixUser ?>">
            <input type="hidden" name="ticket_user_id" value="<?= $_SESSION['user_id'] ?>">
            <input type="hidden" name="user_email" value="<?= $_SESSION['user_email'] ?>">

            <div class="row gx-3">
                <!-- Subject -->
                <div class="col-md-6 mb-3">
                    <label for="subject" class="form-label">Subject</label>
                    <input type="text" class="form-control" name="subject" id="subject" required>
                </div>

                <!-- Issue Type -->
                <div class="col-md-6 mb-3">
                    <label for="issue-type" class="form-label">Issue Type</label>
                    <select class="form-select form-control" id="issue-type" name="issue_type" required>
                        <option value="">Select Issue Type</option>
                        <?php foreach ($projectsType as $projectType): ?>
                            <option value="<?= $projectType['project_type'] . '|' . $projectType['project_id'] . '|' . $projectType['folder_id'] . '|' . $projectType['id'] ?>">
                                <?= htmlspecialchars($projectType['project_type']) ?>
                            </option>
                        <?php endforeach ?>
                    </select>
                </div>

                <!-- Priority -->
                <div class="col-md-6 mb-3">
                    <label for="priority" class="form-label">Priority</label>
                    <select class="form-select form-control" id="priority" name="priority" required>
                        <option value="">Select Priority</option>
                        <option value="Low">Low</option>
                        <option value="Medium">Medium</option>
                        <option value="High">High</option>
                    </select>
                </div>

                <!-- Attachment -->
                <div class="col-md-6 mb-3">
                    <label for="attachment" class="form-label">Attachment</label>
                    <input type="file" class="form-control" name="attachment" id="attachment">
                </div>

                <!-- Description (full width) -->
                <div class="col-12 mb-4">
                    <label for="description" class="form-label">Description</label>
                    <textarea class="form-control" id="description" name="description" rows="4" required></textarea>
                </div>
            </div>

            <button type="submit" class="btn btn-success w-100">
                <i class="bi bi-ticket-fill me-1"></i> Create Ticket
            </button>
        </form>
    </div>

    <div class="styled-table mt-2">
        <table id="ticketTable" class="table table-striped styled-table w-100">
            <thead>
                <tr>
                    <th>Task ID <i class="bi bi-funnel filter-icon"></i>
                        <div class="filter-dropdown"></div>
                    </th>
                    <th>Subject <i class="bi bi-funnel filter-icon"></i>
                        <div class="filter-dropdown"></div>
                    </th>
                    <th>Issue Type <i class="bi bi-funnel filter-icon"></i>
                        <div class="filter-dropdown"></div>
                    </th>
                    <th>Priority <i class="bi bi-funnel filter-icon"></i>
                        <div class="filter-dropdown"></div>
                    </th>
                    <th>Description</th>
                    <th>Date Created <i class="bi bi-funnel filter-icon"></i>
                        <div class="filter-dropdown"></div>
                    </th>
                    <th>Status <i class="bi bi-funnel filter-icon"></i>
                        <div class="filter-dropdown"></div>
                    </th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>

<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../vendor/datatables/jquery.dataTables.js"></script>
<script src="../vendor/datatables/dataTables.bootstrap4.js"></script>

<script>
    $(document).ready(function() {
        const userId = "<?= $_SESSION['user_id'] ?>";
        const userEmail = "<?= $_SESSION['user_email'] ?>";
        function getStage() {
            $.ajax({
                url: "getTaskStage.php",
                type: "GET",
                data: { user_id: userId },
                dataType: "json",
                success: function(response) {
                    console.log("Stage update response:", response);
                    
                },
                error: function(xhr, status, error) {
                    console.error("AJAX Error:", error);
                }
            });
        }

        const columnsToFilter = [0, 1, 2, 3, 5, 6];
        const openDropdowns = new Set();

        // Initialize DataTable
        const table = $('#ticketTable').DataTable({
            data: [],
            columns: [{
                    data: "task_id"
                },
                {
                    data: "subject"
                },
                {
                    data: "issue_type"
                },
                {
                    data: "priority"
                },
                {
                    data: "description"
                },
                {
                    data: "created_at"
                },
                {
                    data: "status"
                },
                {
                    data: "actions"
                }
            ],
            order: [
                [5, 'desc']
            ],
            language: {
                emptyTable: "No tickets found"
            }
        });

        // Setup filter dropdown toggling
        function setupFilters() {
            columnsToFilter.forEach(function(colIdx) {
                const th = $('#ticketTable thead th').eq(colIdx);
                const dropdown = th.find('.filter-dropdown');

                th.find('.filter-icon').off('click').on('click', function(e) {
                    e.stopPropagation();

                    if (openDropdowns.has(colIdx)) {
                        dropdown.hide();
                        openDropdowns.delete(colIdx);
                    } else {
                        $('.filter-dropdown').hide();
                        openDropdowns.clear();

                        dropdown.show();
                        openDropdowns.add(colIdx);

                        // Focus search input if present
                        dropdown.find('input[type=search]').focus();
                    }
                });

                // Prevent dropdown hide when clicking inside dropdown (search input or checkboxes)
                dropdown.off('click').on('click', function(e) {
                    e.stopPropagation();
                });
            });
        }

        // Populate filter dropdown with unique values + search input + checkboxes
        function populateFilters(data) {
            columnsToFilter.forEach(function(colIdx) {
                const uniqueValues = new Set();

                data.forEach(row => {
                    let val = row[table.column(colIdx).dataSrc()];
                    if (colIdx === 6) val = $('<div>').html(val).text().trim(); // Strip HTML from Status column
                    if (val) uniqueValues.add(val);
                });

                const sorted = Array.from(uniqueValues).sort();
                const th = $('#ticketTable thead th').eq(colIdx);
                const dropdown = th.find('.filter-dropdown');
                dropdown.empty();

                // Search box inside filter dropdown
                dropdown.append(`<input type="search" placeholder="Search..." class="filter-search" data-col="${colIdx}">`);

                // "Select All" checkbox (checked by default, but actual options unchecked)
                dropdown.append(`<label><input type="checkbox" class="filter-opt-all" data-col="${colIdx}" checked> <strong>Select All</strong></label>`);

                // Individual filter options (unchecked by default)
                sorted.forEach(val => {
                    dropdown.append(`<label><input type="checkbox" class="filter-opt" data-col="${colIdx}" value="${val}"> ${val}</label>`);
                });

                dropdown.append(`<button class="apply-filter" data-col="${colIdx}">Apply Filter</button>`);
            });

            // Handle search inside dropdown
            $('.filter-search').off('input').on('input', function() {
                const col = $(this).data('col');
                const filterText = $(this).val().toLowerCase();

                const dropdown = $(this).closest('.filter-dropdown');
                dropdown.find('.filter-opt').each(function() {
                    const labelText = $(this).parent().text().toLowerCase();
                    if (labelText.indexOf(filterText) > -1) {
                        $(this).parent().show();
                    } else {
                        $(this).parent().hide();
                    }
                });
            });

            // Select All toggle logic
            $('.filter-opt-all').off('change').on('change', function() {
                const col = $(this).data('col');
                const checked = $(this).is(':checked');
                $(`.filter-opt[data-col="${col}"]`).prop('checked', checked);
            });

            // Individual checkbox toggle logic
            $('.filter-opt').off('change').on('change', function() {
                const col = $(this).data('col');
                const allCount = $(`.filter-opt[data-col="${col}"]`).length;
                const checkedCount = $(`.filter-opt[data-col="${col}"]:checked`).length;
                const selectAllBox = $(`.filter-opt-all[data-col="${col}"]`);

                if (checkedCount === allCount) {
                    selectAllBox.prop('checked', true);
                } else {
                    selectAllBox.prop('checked', false);
                }
            });

            // Apply Filter button click
            $('.apply-filter').off('click').on('click', function(e) {
                e.stopPropagation();
                applyFilters();
            });
        }

        // Apply filters on DataTable based on checked boxes
        function applyFilters() {
            columnsToFilter.forEach(function(colIdx) {
                // Get checked filter values
                const checked = $(`.filter-opt[data-col="${colIdx}"]:checked`).map(function() {
                    return $(this).val();
                }).get();

                if (checked.length === 0) {
                    // No filter selected => clear search for this column
                    table.column(colIdx).search('', true, false);
                } else {
                    // Escape regex special characters
                    const regex = checked.map(v => v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
                    // Apply regex search with word boundary for exact matches
                    table.column(colIdx).search(regex, true, false);
                }
            });

            table.draw();

            // Hide filter dropdowns after applying filters
            $('.filter-dropdown').hide();
            openDropdowns.clear();

            // Show "No tickets found" if filtered data is empty
            if (table.rows({
                    filter: 'applied'
                }).data().length === 0) {
                $('#ticketTable tbody').html(`<tr><td colspan="8" class="text-center">No tickets found</td></tr>`);
            }
        }

        // Fetch ticket data via AJAX and populate DataTable
        function fetchTickets() {
            $.ajax({
                url: "get_tickets.php",
                type: "GET",
                data: {
                    user_id: userId
                },
                dataType: "json",
                success: function(response) {
                     
                    table.clear();

                    if (response.length === 0) {
                        $('#ticketTable tbody').html(`<tr><td colspan="8" class="text-center">No tickets found</td></tr>`);
                        return;
                    }

                    response.forEach(ticket => {
                        const viewBtn = ticket.task_id ?
                            `<a href="comment_get.php?task_id=${ticket.task_id}&btrix24_user=${ticket.bitrix_user_id}" class="btn btn-sm btn-primary">View</a>` :
                            "N/A";

                        // Use plain status text but show badge for UI
                        const statusText = ticket.status || "N/A";
                        const statusBadge = `<span class="badge" style="background-color: #${ticket.stage_color || '999'}; color: white;">${statusText}</span>`;

                        table.row.add({
                            task_id: ticket.task_id ?? "N/A",
                            subject: ticket.subject,
                            issue_type: ticket.issue_type,
                            priority: ticket.priority,
                            description: ticket.description,
                            created_at: ticket.created_at,
                            status: statusBadge,
                            actions: viewBtn
                        });
                    });

                    table.draw();

                    setupFilters();
                    populateFilters(response);
                },
                error: function() {
                    $('#ticketTable tbody').html(`<tr><td colspan="8" class="text-center text-danger">Failed to load tickets.</td></tr>`);
                }
            });
        }

        // Close dropdowns on clicking outside
        $(document).on('click', function() {
            $('.filter-dropdown').hide();
            openDropdowns.clear();
        });

        fetchTickets();
        getStage();
    });
</script>