<?php $this->load->view('admin/includes/head'); ?>
<?php $this->load->view('admin/includes/sidebar'); ?>
<?php $this->load->view('admin/includes/topbar'); ?>


<style>
    /* Reset and base styles */
    .table tr:hover,
    .table-hover tbody tr:hover {
        background-color: transparent !important;
    }

    /* Modal styles */
    .modal {
        overflow: hidden !important;
    }

    .modal-dialog {
        max-width: 600px;
        margin: 1.75rem auto;
    }

    .modal-content {
        border: none;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        max-height: calc(100vh - 3.5rem);
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .modal-header {
        background-color: var(--devotee-table-header-bg);
        padding: 1rem 1.5rem;
        border-bottom: 2px solid #dee2e6;
    }

    .modal-body {
        padding: 1.5rem;
        overflow-y: auto;
        flex: 1 1 auto;
        max-height: calc(100vh - 200px);
        scrollbar-width: none;
        /* Firefox */
        -ms-overflow-style: none;
        /* IE and Edge */
    }

    .modal-body::-webkit-scrollbar {
        display: none;
        /* Chrome, Safari, Opera */
    }

    /* Content sections */
    .event-details,
    .contributions-list,
    .your-contribution {
        background-color: #ffffff;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 1.25rem;
        margin-bottom: 1.25rem;
    }

    /* List styles */
    .list-group-item {
        margin-bottom: 0.5rem;
        border: 1px solid #dee2e6 !important;
        border-radius: 6px !important;
        padding: 0.875rem;
        transition: all 0.2s ease;
    }

    .list-group-item:last-child {
        margin-bottom: 0;
    }

    .list-group-item:hover {
        background-color: #f8f9fa;
    }

    /* Form styling */
    .contribution-form {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 1.25rem;
        margin-top: 1rem;
    }

    .form-control {
        border: 1px solid #ced4da;
    }

    /* Utilities */
    .section-divider {
        height: 1px;
        background-color: #dee2e6;
        margin: 1.25rem 0;
    }

    /* Button and badge styles */
    .btn-close {
        opacity: 0.5;
        transition: opacity 0.2s ease;
    }

    .btn-close:hover {
        opacity: 1;
    }

    .btn-close-white {
        filter: brightness(0) invert(1);
    }

    .btn {
        padding: 0.375rem 1rem;
    }

    .badge {
        font-size: 0.875rem;
    }

    /* Alert styles */
    .alert {
        margin-bottom: 15px;
        border-radius: 6px;
    }

    /* Animation styles */
    .contribution-form {
        transition: all 0.3s ease-in-out;
    }

    /* Fix for modal backdrop */
    .modal-backdrop {
        opacity: 0.5;
    }
</style>

<div class="container-fluid px-4">
    <h1 class="mt-4">Participant</h1>

    <div class="card mb-4">
        <div class="card-header">
            Event List
        </div>
        <div class="card-body">
            <?php if (isset($error)): ?>
                <div class="alert alert-danger"><?= $error ?></div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead class="bg-dark text-white">
                            <tr>
                                <th>Event Period</th>
                                <th>Event Name</th>
                                <th>Event Type</th>
                                <th>Devotees</th>
                                <th>Target</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($participants as $index => $event): ?>
                                <tr>
                                    <td>
                                        <span class="text-success" style="color: black !important;">
                                            <i class="fas fa-calendar-alt me-2"></i>
                                            <?= $event->startDate ?> to <?= $event->endDate ?>
                                        </span>
                                    </td>
                                    <td>
                                        <strong class="text-primary"><?= $event->refDataName ?></strong>
                                    </td>
                                    <td>
                                        <span class="text-muted" style="color: black !important;"><?= $event->refDataName1 ?></span>
                                    </td>
                                    <td>

                                        <?= isset($event->resultd[0]->count) ? $event->resultd[0]->count : 0 ?>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div>
                                                <?php
                                                $percentage = ($event->resultd[0]->sum / $event->maxCount) * 100;
                                                $progressClass = $percentage >= 90 ? 'bg-danger' : ($percentage >= 70 ? 'bg-warning' : 'bg-success');
                                                ?>
                                                <div class="progress-bar <?= $progressClass ?>"
                                                    role="progressbar"
                                                    style="width: <?= $percentage ?>%"
                                                    aria-valuenow="<?= $percentage ?>"
                                                    aria-valuemin="0"
                                                    aria-valuemax="100">
                                                </div>
                                            </div>
                                            <small class="text-muted" style="color: black !important;">
                                                <?= $event->resultd[0]->sum ?>/<?= $event->maxCount ?>
                                            </small>
                                        </div>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary"
                                            data-bs-toggle="modal"
                                            data-bs-target="#modal<?= $index ?>">
                                            Participate
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php foreach ($participants as $index => $event): ?>
                    <div class="card mb-3 border-success" style="display: none;">
                        <div class="card-header bg-light">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <strong><?= $event->startDate ?> to <?= $event->endDate ?></strong>
                                </div>
                                <div class="text-success">
                                    <i class="fas fa-circle"></i>
                                </div>
                            </div>
                        </div>
                        <div class="card-body bg-dark text-white rounded">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="card-title text-info mb-1"><?= $event->refDataName ?></h5>
                                    <p class="mb-2 text-warning"><?= $event->refDataName1 ?></p>
                                    <p class="mb-1"><i class="fas fa-user"></i> Devotees: (<?= $event->resultd[0]->count ?>)</p>
                                    <p class="mb-1"># Target: <?= $event->maxCount ?> &nbsp;&nbsp;&nbsp; # Count: <?= $event->resultd[0]->sum ?></p>
                                </div>
                                <div>
                                    <button class="btn btn-outline-light" data-bs-toggle="modal" data-bs-target="#modal<?= $index ?>">
                                        <i class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Modal Structure -->
                    <div class="modal fade" id="modal<?= $index ?>" tabindex="-1" aria-labelledby="modalLabel<?= $index ?>" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content">
                                <div class="modal-header text-white" style="background-color: var(--devotee-table-header-bg);">
                                    <h5 class="modal-title" id="modalLabel<?= $index ?>">
                                        Event Contributions
                                    </h5>
                                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>

                                <!-- Event Details Section -->
                                <div class="modal-body">
                                    <div class="event-details">
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <h6 class="text-primary mb-0"><?= $event->refDataName ?></h6>
                                            <span class="badge bg-info"><?= $event->refDataName1 ?></span>
                                        </div>

                                        <div class="row g-3">
                                            <div class="col-6">
                                                <div class="stats-item">
                                                    <span class="text-muted">Devotees</span><br>
                                                    <span class="fw-bold"><?= $event->resultd[0]->count ?></span>
                                                </div>
                                            </div>
                                            <div class="col-6">
                                                <div class="stats-item">
                                                    <span class="text-muted">Total Count</span><br>
                                                    <span class="fw-bold"><?= $event->resultd[0]->sum ?>/<?= $event->maxCount ?></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="section-divider"></div>

                                    <div class="your-contribution your-contribution-<?= $index ?> bg-light p-3 rounded mb-4">
                                        <h6 class="mb-2">Your Total Contribution</h6>
                                        <span class="fs-4 fw-bold text-success"><?= count(@$event->resultd[0]->Datas) ?? 0 ?></span>
                                    </div>

                                    <!-- Contributions List -->
                                    <!-- Contributions List -->
                                    <div class="contributions-list">
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <h6 class="mb-0">Recent Contributions</h6>
                                            <button class="btn btn-sm btn-primary add-contribution-btn" data-index="<?= $index ?>">
                                                <i class="fas fa-plus"></i> Add New
                                            </button>
                                        </div>

                                        <div class="contributions-container-<?= $index ?>">
                                            <?php
                                            $loggedInUserId = $this->session->userdata('id') ?? '';
                                            $userContributions = [];

                                            if (!empty($event->resultd) && !empty($event->resultd[0]->Datas)) {
                                                // Filter only this user's contributions
                                                $userContributions = array_filter($event->resultd[0]->Datas, function ($d) use ($loggedInUserId) {
                                                    return $d->memberId == $loggedInUserId;
                                                });
                                            }
                                            ?>

                                            <?php if (!empty($userContributions)): ?>
                                                <div class="list-group">
                                                    <?php foreach ($userContributions as $d): ?>
                                                        <div class="list-group-item">
                                                            <div class="d-flex justify-content-between align-items-center">
                                                                <div>
                                                                    <i class="fas fa-calendar-alt text-muted me-2"></i>
                                                                    <small class="text-muted">
                                                                        <?= $d->cartCreDate ?> (<?= $d->cartCreTime ?>)
                                                                    </small>
                                                                </div>
                                                                <span class="badge bg-success rounded-pill">
                                                                    #<?= $d->count ?>
                                                                </span>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php else: ?>
                                                <p class="text-muted text-center py-3">No contributions yet</p>
                                            <?php endif; ?>
                                        </div>
                                    </div>




                                    <!-- Contribution Form -->
                                    <div class="contribution-form-<?= $index ?>" style="display: none;">
                                        <div class="row g-3 mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label fw-bold">Date</label>
                                                <input type="date"
                                                    class="form-control"
                                                    name="date"
                                                    min="<?= $event->startDate ?>"
                                                    max="<?= $event->endDate ?>"
                                                    value="<?= date('Y-m-d') ?>"
                                                    required>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label fw-bold">Count</label>
                                                <input type="number"
                                                    class="form-control count-input"
                                                    name="count"
                                                    min="1"
                                                    max="<?= $event->maxCount - ($event->resultd[0]->sum ?? 0) ?>"
                                                    placeholder="Enter count (Max: <?= $event->maxCount - ($event->resultd[0]->sum ?? 0) ?>)"
                                                    required>
                                                <div class="form-text text-muted">
                                                    Available count: <?= $event->maxCount - ($event->resultd[0]->sum ?? 0) ?>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Hidden fields with dynamic values -->
                                        <input type="hidden" name="memberId" value="<?= $this->session->userdata('id') ?? '' ?>" />
                                        <input type="hidden" name="memberName" value="<?= $this->session->userdata('refDataName') ?? '' ?>" />
                                        <input type="hidden" name="eventName" value="<?= $event->refDataName ?>" />
                                        <input type="hidden" name="eventId" value="<?= $event->_id ?? '' ?>" />
                                        <input type="hidden" name="itemName" value="<?= $event->refDataName1 ?>" />
                                        <input type="hidden" name="clientId" value="<?= ApiBaseUrl()['clientID'] ?? '' ?>" />

                                        <div class="text-end">
                                            <button type="button" class="btn btn-secondary cancel-add-btn" style="color: #fff; background-color: #b02135; border-color: #ffffff; box-shadow: none;" data-index="<?= $index ?>">
                                                Cancel
                                            </button>
                                            <button type="button" class="btn btn-primary submit-contribution" data-index="<?= $index ?>">
                                                Submit
                                            </button>
                                        </div>
                                    </div>



                                </div>
                            </div>
                        </div>
                    </div>
        </div>

        <!-- JavaScript -->
        <script>
            $(document).ready(function() {
                // Utility function for form validation
                function validateFormData(data) {
                    const required = ['date', 'count', 'memberId', 'memberName', 'eventName', 'eventId'];
                    const missing = [];

                    required.forEach(field => {
                        if (!data[field]) missing.push(field);
                    });

                    if (missing.length) {
                        console.error('Missing required fields:', missing);
                        return false;
                    }
                    return true;
                }

                // Helper function to show alerts
                function showAlert(message, type = 'warning') {
                    const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show mt-2 count-alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;

                    // Remove any existing alerts
                    $('.count-alert').remove();

                    // Add new alert after the count input
                    $('.contribution-form input[name="count"]').after(alertHtml);

                    // Auto dismiss after 3 seconds
                    setTimeout(() => {
                        $('.count-alert').fadeOut('slow', function() {
                            $(this).remove();
                        });
                    }, 3000);
                }

                // Count validation function
                function setupCountValidation(index) {
                    const maxCount = parseInt($(`#modal${index} input[name="count"]`).attr('max'));
                    const countInput = $(`#modal${index} input[name="count"]`);

                    countInput.on('input', function() {
                        const value = parseInt($(this).val());

                        if (isNaN(value)) {
                            $(this).val('');
                            return;
                        }

                        if (value > maxCount) {
                            $(this).val(maxCount);
                            showAlert(`Maximum allowed count is ${maxCount}`, 'warning');
                        } else if (value < 1) {
                            $(this).val(1);
                            showAlert('Minimum count should be 1', 'warning');
                        }
                    });
                }

                // Show contribution form with smooth scroll
                $('.add-contribution-btn').click(function() {
                    const index = $(this).data('index');
                    const form = $(`.contribution-form-${index}`);
                    const modalBody = form.closest('.modal-body');

                    form.slideDown(400, function() {
                        modalBody.animate({
                            scrollTop: form.offset().top - modalBody.offset().top + modalBody.scrollTop()
                        }, 500);
                    });

                    $(this).hide();
                    setupCountValidation(index);
                });

                // Cancel add contribution with scroll to top
                $('.cancel-add-btn').click(function() {
                    const index = $(this).data('index');
                    const form = $(`.contribution-form-${index}`);
                    const modalBody = form.closest('.modal-body');

                    modalBody.animate({
                        scrollTop: 0
                    }, 500, function() {
                        form.slideUp(400);
                        $(`.add-contribution-btn[data-index="${index}"]`).show();
                    });
                });

                // Handle form submission
                $('.submit-contribution').off('click').on('click', function() {
                    const index = $(this).data('index');
                    const form = $(`.modal-body .contribution-form-${index}`);

                    // Validate count before proceeding
                    const count = parseInt(form.find('input[name="count"]').val());
                    const maxCount = parseInt(form.find('input[name="count"]').attr('max'));

                    if (!count || count < 1) {
                        showAlert('Please enter a valid count', 'danger');
                        return false;
                    }

                    if (count > maxCount) {
                        showAlert(`Count cannot exceed ${maxCount}`, 'danger');
                        return false;
                    }

                    // Get form data
                    const formData = {
                        date: form.find('input[name="date"]').val(),
                        count: count,
                        memberId: form.find('input[name="memberId"]').val(),
                        memberName: form.find('input[name="memberName"]').val(),
                        eventName: form.find('input[name="eventName"]').val(),
                        eventId: form.find('input[name="eventId"]').val(),
                        itemName: form.find('input[name="itemName"]').val(),
                        clientId: form.find('input[name="clientId"]').val()
                    };

                    // Validate form data
                    if (!validateFormData(formData)) {
                        showAlert('Please fill all required fields', 'danger');
                        return false;
                    }

                    const submitBtn = $(this);
                    submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Submitting...');

                    // Format date and time
                    const dateObj = new Date(formData.date);
                    const formattedDate = `${(dateObj.getMonth() + 1).toString().padStart(2, '0')}/${dateObj.getDate().toString().padStart(2, '0')}/${dateObj.getFullYear()}`;
                    const formattedTime = new Date().toLocaleTimeString('en-US', {
                        hour: 'numeric',
                        minute: '2-digit',
                        hour12: true
                    });

                    // Prepare API payload
                    const payload = {
                        dataJson: {
                            memberId: formData.memberId,
                            memberName: formData.memberName,
                            eventName: formData.eventName,
                            eventId: formData.eventId,
                            itemName: formData.itemName,
                            count: count,
                            cartCreDate: formattedDate,
                            cartCreTime: formattedTime
                        },
                        clientId: formData.clientId
                    };

                    // Make API request
                    $.ajax({
                        url: '<?= base_url("admin/dashboard/addParticipateEvent") ?>', // Updated path
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(payload),
                        success: function(response) {
                            if (response && response.success === true) {
                                // Update UI with new contribution
                                const newContribution = `
                        <div class="list-group-item border-0 border-bottom">
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">
                                    ${formattedDate} (${formattedTime})
                                </small>
                                <span class="badge bg-success rounded-pill">
                                    #${count}
                                </span>
                            </div>
                        </div>
                    `;

                                // Add to container
                                const container = $(`.contributions-container-${index}`);
                                if (container.find('.list-group').length) {
                                    container.find('.list-group').prepend(newContribution);
                                } else {
                                    container.html(`<div class="list-group">${newContribution}</div>`);
                                }

                                const contributionEl = $(`.your-contribution-${index} span`);
                                const currentTotal = parseInt(contributionEl.text()) || 0;
                                const newTotal = currentTotal + parseInt(count);
                                contributionEl.text(newTotal);


                                // Show success message
                                $('.modal-body').prepend(`
                        <div class="alert alert-success alert-dismissible fade show">
                            <strong>Success!</strong> Contribution added successfully
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    `);

                                // Reset form
                                form.find('input[type="text"], input[type="number"], input[type="date"]').val('');

                                // Hide form and show add button
                                $(`.contribution-form-${index}`).slideUp();
                                $(`.add-contribution-btn[data-index="${index}"]`).show();

                                // Refresh page after delay
                                // setTimeout(() => location.reload(), 2000);
                            } else {
                                showAlert(response.message || response.msg || 'Failed to add contribution', 'danger');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('Ajax Error:', {
                                status,
                                error,
                                response: xhr.responseText
                            });
                            showAlert('Error occurred while adding contribution', 'danger');
                        },
                        complete: function() {
                            submitBtn.prop('disabled', false).html('Submit');
                        }
                    });
                });
            });
        </script>

        <!-- Include Bootstrap JS (if not already included) -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <?php endforeach; ?>
<?php endif; ?>
    </div>
</div>
</div>

<?php $this->load->view('admin/includes/footer'); ?>