<?php
if ($action == 'addParticipateEvent') {
?>
    <form action="<?= base_url("Admin/Dashboard/saveParticipateEvent") ?>" method="POST" id="AddForm">
        <!-- Event Details -->
        <div class="event-details mb-1">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <table class="table">
                    <tr>
                        <td style="text-align: left!important;">
                            <p style="line-height: 1;font-size: 20px !important;"><b>Event Name</b></p>
                        </td style="text-align: left!important;">
                        <td>
                            <p class="text-primary mb-0 text-dark" style="line-height: 1;font-size: 17px !important;"><?= $data['refDataName'] ?></p>
                            <p style="line-height: 1;font-size: 20px !important;"><small>( <?= $data['refDataName1'] ?> )</small></p>
                        </td>
                    </tr>

                    <!-- <tr>
                        <td>
                            <p style="line-height: 1;font-size: 17px !important;"><b>Date</b></p>
                        </td>
                        <td>
                            <p style="line-height: 1;font-size: 17px !important;"><?= date('M d, Y', strtotime($data['startDate'])) ?> - <?= date('M d, Y', strtotime($data['endDate'])) ?></p>
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <p style="line-height: 1;font-size: 17px !important;"> <b>Target Count</b></p>
                        </td>
                        <td>
                            <p style="line-height: 1;font-size: 17px !important;"> <?= number_format(@$data['maxCount'] ?? 0) ?></p>
                        </td>
                    </tr> -->
                </table>

            </div>
        </div>


        <?php
        // echo $data['refDataName'];
        // echo "<br><br>";
        $groupDetails = @getUserDetails()->data[0]->groupDetails ?? [];
        $groupName = '';
        if (!empty($groupDetails)) {

            foreach ($groupDetails as $item) {
                if ($item->eventId == $data['_id']) {
                    $groupName = $item->groupName;
                    break; // Stop once matched
                }
            }
            $matchedData;
        }
        ?>
        <!-- Contribution Form -->
        <div class="contribution-form-0">

            <div class="row g-3 mb-3">
                <div class="col-md-6">
                    <label class="form-label fw-bold">Select Date</label>
                    <div style="position: relative;">
                        <input type="text"
                            class="datepicker-events form-control form-control-sm date-time-placeholder"
                            id="EvntDate"
                            style="height: 38px !important; padding-right: 35px;border: 1px solid #ced4da!important;"
                            name="date"
                            min="<?= $data['startDate'] ?>"
                            max="<?= $data['endDate'] ?>"
                            value="<?= date('m/d/Y') ?>" readonly required>
                        <i class="fa fa-calendar"
                            style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); color: #555;"></i>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold">Count</label>
                    <input type="number"
                        class="form-control count-input"
                        name="count"
                        id="EvtCount" oninput="countValidateEvt(this.value)"
                        min="1" style="border: 1px solid #ced4da!important;"
                        max="<?= $data['maxCount'] - @$data['resultd'][0]['sum'] ?>"
                        placeholder="Enter count (Max: <?= number_format($data['maxCount'] - @$data['resultd'][0]['sum']) ?>)"
                        required>

                </div>

                <div class="col-md-12 d-flex align-items-center" style="gap: 10px;">
                    <input type="checkbox" id="submitAsGroup" name="submitAsGroup" style="height: 25px; width: 25px;">
                    <label class="form-label fw-bold mb-0" for="submitAsGroup">Submit as a group</label>
                </div>

                <div class="col-md-12 d-none" id="groupNameDiv">
                    <div class="row">
                        <div class="col-sm-6">
                            <label class="form-label fw-bold">Group Name</label>
                            <input type="text"
                                class="form-control"
                                name="groupName"
                                id="groupName" style="border: 1px solid #ced4da!important;"
                                placeholder="Enter group name" value="<?= $groupName ?>" <?= !empty($groupName) ? 'readonly style="background:#d3d3d3;"' : '' ?>>

                        </div>
                        <div class="col-sm-6">
                            <label class="form-label fw-bold">Devotee Count</label>
                            <input type="number"
                                class="form-control" style="border: 1px solid #ced4da!important;"
                                name="devoteeCount"
                                id="devoteeCount"
                                placeholder="Enter devotee count" value="1">

                        </div>
                    </div>

                </div>
                <input type="hidden" name="grpNameHidden" value="<?= $groupName ?>">
            </div>
            <!-- Hidden Fields -->
            <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" id="inppEvntName" value="<?= $data['refDataName'] ?>">
            <input type="hidden" name="eventId" id="inppEvntId" value="<?= $data['_id'] ?>">
            <input type="hidden" name="itemName" id="inppEvntName1" value="<?= $data['refDataName1'] ?>">
            <input type="hidden" name="clientId" value="<?= ApiBaseUrl()['clientID'] ?? '' ?>">

            <!-- Form Actions -->
            <hr>
            <div class="row">
                <div class="col-sm-12" style="  display: flex;justify-content: space-between;">
                    <button type="button" class="btn btn-secondary cancel-add-btn"
                        style="color: #fff; background-color: #b02135; border-color: #ffffff; box-shadow: none;    border-radius: 7px !important;"
                        data-index="0">
                        Cancel
                    </button>

                    <button type="submit" class="btn btn-primary submit-contribution" data-index="0" style="background-color: #005d4b!important;    border-radius: 7px !important;">
                        Submit
                    </button>
                </div>
                <!-- <div class="col-sm-6 text-end">
                    <button type="submit" class="btn btn-primary submit-contribution" data-index="0" style="background-color: #005d4b!important;    border-radius: 7px !important;">
                        Submit
                    </button>
                </div> -->


            </div>
        </div>
    </form>
    <script>
        $(document).ready(function() {
            $("#EvntDate").datepicker({
                dateFormat: "mm/dd/yy",
                minDate: "<?= $data['startDate'] ?>",
                maxDate: "<?= $data['endDate'] ?>",
                showAnim: "fadeIn",
                appendTo: '#partishipent_events-Modal'
            });
            $('#submitAsGroup').change(function() {
                if ($(this).is(':checked')) {
                    $('#groupNameDiv').removeClass('d-none');
                    $("#groupName").attr("required", true);
                } else {
                    // $("#groupName").val('');
                    $('#groupNameDiv').addClass('d-none');
                    $("#groupName").removeAttr("required");
                }
            });
        });

        $(document).on('click', '#EvntDate', function() {
            $(this).datepicker("show");
        });
        $('#AddForm').on('submit', function(e) {
            e.preventDefault(); // Prevent default form submission

            // Create a FormData object
            var formData = new FormData(this);
            var url = $('#AddForm').attr('action');
            loader.on();
            $.ajax({
                url: url, // PHP file to handle the upload
                type: 'POST',
                data: formData,
                contentType: false, // Prevent jQuery from overriding the content type
                processData: false, // Prevent jQuery from processing the data
                success: function(response) {
                    loader.off();
                    // $('#response').html(response);
                    console.log(response);
                    try {
                        // Ensure response is a JSON object
                        // var res = typeof response === 'string' ? JSON.parse(response) : response;
                        var res = response;
                        console.log(res.message);
                        if (res.success) {
                            // $.notify(res.message,"success");
                            // swal({
                            //         html: true,
                            //         title: res.message,
                            //         type: "success",
                            //         confirmButtonText: 'OK',
                            //         confirmButtonColor: 'var(--main-color-new-theme)',
                            //     },

                            //     function() {
                            //         loader.on();
                            //         window.location.reload();


                            //     });
                            alert(res.message);
                             $("#partishipent_events-Modal").modal("hide");
                             loader.on();
                            window.location.reload();

                        } else {
                            // $.notify(res.message, "error");
                            alert(res.message);
                        }



                    } catch (err) {
                        loader.off();
                        console.error("Error parsing response:", err);

                        // $.notify("Invalid response format.", "error");
                        alert("Invalid response format.");
                    }

                },
                error: function(xhr, status, error) {
                    loader.off();
                    // $.notify("Invalid response format.", "error");
                    alert("Invalid response format.");
                }
            });
        });
          function countValidateEvt(count) {
        console.log("count: " + count);
        let EvtCount = parseInt($("#EvtCount").attr('max'));
        if (count <= 0) {
            alert("Please enter more than 0");
            $("#EvtCount").val('');
        } else if (count > EvtCount) {
            alert("Please enter less or equal " + EvtCount);
            $("#EvtCount").val('');
        }
    }
    </script>
<?php
} else {
?>
    <p class="text-danger text-center">Invalid Action</p>
<?php
}
?>
<script>
    $('.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);
    });

    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');
            }
        });
    }
    // $(document).on('click', '#EvntDate', function() {
    //     console.log("EvntDate");
    //     $("#EvntDate").datepicker({
    //         dateFormat: "mm/dd/yy",
    //         minDate: "<?= $data['startDate'] ?>",
    //         maxDate: "<?= $data['endDate'] ?>"
    //     });

    // });
</script>
<script>
    /*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


    // Show contribution form with smooth scroll


    // 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}`);
        console.log("index: " + 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/add-participate-event") ?>',
            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>