<?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>
                            <p style="line-height: 1;font-size: 17px !important;"><b>Event Name</b></p>
                        </td>
                        <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: 17px !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;"
                            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"
                        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"
                                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"
                                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");
        });
    </script>
<?php
} else {
?>
    <p class="text-danger text-center">Invalid Action</p>
<?php
}
?>
<script>
    // $(function() {
    //     $("#EvntDate").datepicker({
    //         dateFormat: "mm/dd/yy",
    //         minDate: new Date("<?= $data['startDate'] ?>", ),
    //         maxDate: new Date("<?= $data['endDate'] ?>")
    //     });
    // });

    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>
<script>
    $('#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();


                            });

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



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

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

            },
            error: function(xhr, status, error) {
                loader.off();
                $.notify("Invalid response format.", "error");
            }
        });
    });
</script>