{% extends 'base_dashboard.html' %}
{% load static %}


{% block attendees %}

  <div class="row">
    <div class="col-md-12">
        <div class="card card-round">
        <div class="card-header">
            <div class="card-head-row card-tools-still-right" >
            <h4 class="card-title">RSVP List</h4>
             
            <div class="card-tools" style="display: flex; align-items: center;">
                   
                <!-- Add a button to send bulk QR codes to guests -->
                <button class="btn btn-sm btn-primary" onclick="sendBulkBirthdayQRCodes()">
                    Bulk Birthday
                </button>

                <button class="btn btn-warning btn-sm" onclick="resetStatus()" id="resetStatusBtn">
                    Reset Status
                </button> 
            </div>
            </div>
            <p class="card-category">  </p>
        </div>
            <div class="card-body p-0 pb-3">
            <div class="table-responsive">
                {% if guests %}
                 
                <div class="container-fluid">       
                <table class="table bg-light myTable" id="attendeeTable">
                    <thead class="thead-light">
                    <tr>
                    <th scope="col"><input type="checkbox" id="selectAll"></th>
                    <!-- <th scope="col">#</th> -->
                    <th scope="col">Full Name</th>
                    <th scope="col">Email</th>
                    <th scope="col">Phone</th>
                    <th scope="col">Spouse's Name</th>
                    <th scope="col">With Driver</th>
                    <th scope="col">Date</th>
                    <th scope="col">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% for guest in guests %}
                      <tr data-guest-id="{{ guest.id }}">
                        <td><input type="checkbox" class="rsvp-checkbox" value="{{ guest.id }}"></td>
                        <!-- <td>{{ forloop.counter }}</td> -->
                        <td>{{ guest.first_name }} {{ guest.last_name }}</td>                                  
                        <td>{{guest.email}}</td>
                        <td>{{guest.phone}}</td>
                        <td>{{guest.spouse|default:"-"}}</td>
                        <td>{% if guest.has_driver %}Yes{% else %}No{% endif %}</td>
                        <td>{{guest.created_at}}</td>
                          <td class="d-flex gap-1">

                            {% if guest.is_sent_birthday %}
                            <button class="btn btn-light text-primary btn-sm" style="cursor: not-allowed;">
                                <i class="fas fa-circle-check"></i>
                            </button>
                            {% else %}
                            <button onclick="sendBirthdayQRcode({{ guest.id }})" class="btn btn-primary btn-sm" title="Send Birthday QR Code">
                                <i class="fas fa-qrcode"></i>
                            </button>
                            {% endif %}

                            <button onclick="editGuest({{ guest.id }})" class="btn btn-warning btn-sm" title="Edit Guest">
                            <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="deleteGuest({{ guest.id }})" class="btn btn-danger btn-sm" title="Delete Guest">
                            <i class="fas fa-trash"></i>
                            </button>
                          </td>
                      </tr>
                    {% endfor %}
                    </tbody>
                </table>
                 
                </div>
                 
                {% else %}
                <div class="row my-5" style="padding: 50px 0">
                    <h5 class="text-center">Your attendee list is empty.</h5>
                </div>
                {% endif %}
            </div>
            </div>
        </div>
    </div>
  </div>
 
{% endblock %} 
{% block customJS %}
<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editModalLabel">Edit Guest</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="editForm">
          <input type="hidden" id="editGuestId" name="guestId">
          <div class="form-group">
            <label for="editFirstName">First Name</label>
            <input type="text" class="form-control" id="editFirstName" name="first_name" required>
          </div>
          <div class="form-group">
            <label for="editLastName">Last Name</label>
            <input type="text" class="form-control" id="editLastName" name="last_name">
          </div>
          <div class="form-group">
            <label for="editEmail">Email</label>
            <input type="email" class="form-control" id="editEmail" name="email" required>
          </div>
          <div class="form-group">
            <label for="editPhone">Phone</label>
            <input type="text" class="form-control" id="editPhone" name="phone" required>
          </div>
            <div class="form-group">
                <label for="editSpouse">Add Spouse</label>
                <input type="text" class="form-control" id="editSpouse" name="spouse">
            </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="saveChangesBtn">Save changes</button>
      </div>
    </div>
  </div>
</div>

<script>
    // Reset Status Function
    function resetStatus() {
        showConfirm(
            'Reset RSVP Status',
            'Are you sure you want to reset all RSVP statuses? This will mark all guests as not sent.',
            function(confirmed) {
                if (confirmed) {
                    $.ajax({
                        url: "{% url 'reset_rsvp_status' %}",
                        type: 'POST',
                        headers: {
                            'X-CSRFToken': '{{ csrf_token }}'
                        },
                        data: JSON.stringify({}),
                        contentType: 'application/json',
                        beforeSend: function() {
                            $('#resetStatusBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Resetting...');
                        },
                        success: function(response) {
                            if (response.status === 200) {
                                showAlert('RSVP status has been reset successfully!', 'success');
                                setTimeout(() => {
                                    location.reload();
                                }, 1500);
                            } else {
                                showAlert(response.message || 'Failed to reset status.', 'error');
                                $('#resetStatusBtn').prop('disabled', false).html('Reset Status');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('Error:', error);
                            showAlert('An error occurred while resetting status.', 'error');
                            $('#resetStatusBtn').prop('disabled', false).html('Reset Status');
                        }
                    });
                }
            }
        );
    }

    // Send Thanksgiving QR Code Function
    function sendThanksgivingQRcode(rsvpId) {
        const button = $(`button[onclick="sendThanksgivingQRcode(${rsvpId})"]`);
        const originalHTML = button.html();
        
        $.ajax({
            url: "{% url 'send_birthday_qr_code' %}",
            type: 'POST',
            data: {
                'rsvp_id': rsvpId,
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            beforeSend: function() {
                button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
            },
            success: function(response) {
                if (response.status === 200) {
                    showAlert('QR code has been sent to the attendee.', 'success');
                    // Update button appearance
                    button.removeClass('btn-primary')
                            .addClass('btn-light text-secondary')
                            .prop('disabled', true)
                            .attr('onclick', '')
                            .attr('title', 'QR Code Sent')
                            .html('<i class="fas fa-circle-check"></i>');
                } else {
                    showAlert(response.message || 'Failed to send QR code.', 'error');
                    button.prop('disabled', false).html(originalHTML);
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
                showAlert('An error occurred while sending QR code.', 'error');
                button.prop('disabled', false).html(originalHTML);
            }
        });
    }

    // Send Thanksgiving Bulk QR Codes Function
    function sendBulkThanksgivingQRCodes() {
        const selectedRsvps = $('.rsvp-checkbox:checked').map(function() {
            return $(this).val();
        }).get();

        if (selectedRsvps.length === 0) {
            showAlert('Please select at least one RSVP attendee.', 'warning');
            return;
        }

        showConfirm(
            'Send Bulk QR Codes',
            `Are you sure you want to send Thanksgiving QR codes to ${selectedRsvps.length} attendee(s)?`,
            function(confirmed) {
                if (confirmed) {
                    const bulkButton = $('button[onclick="sendBulkThanksgivingQRCodes()"]');
                    const originalBulkHTML = bulkButton.html();
                    
                    $.ajax({
                        url: "{% url 'send_bulk_birthday_qr_codes' %}",
                        type: 'POST',
                        headers: {
                            'X-CSRFToken': '{{ csrf_token }}',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            'rsvp_ids': selectedRsvps
                        }),
                        beforeSend: function() {
                            bulkButton.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Sending...');
                            // Disable all selected checkboxes
                            $('.rsvp-checkbox:checked').prop('disabled', true);
                        },
                        success: function(response) {
                            if (response.status === 200) {
                                showAlert(`Thanksgiving QR codes sent to ${response.sent_count} attendee(s).`, 'success');
                                
                                // Update buttons for successfully sent RSVPs
                                selectedRsvps.forEach(rsvpId => {
                                    const btn = $(`button[onclick="sendThanksgivingQRcode(${rsvpId})"]`);
                                    if (btn.length) {
                                        btn.removeClass('btn-secondary')
                                        .addClass('btn-light text-secondary')
                                        .prop('disabled', true)
                                        .attr('onclick', '')
                                        .attr('title', 'Thanksgiving QR Code Sent')
                                        .html('<i class="fas fa-circle-check"></i>');
                                    }
                                });
                                
                                // Reset checkboxes
                                $('.rsvp-checkbox').prop('checked', false).prop('disabled', false);
                                $('#selectAll').prop('checked', false);
                            } else {
                                showAlert(response.message || 'Failed to send QR codes.', 'error');
                                $('.rsvp-checkbox:checked').prop('disabled', false);
                            }
                            
                            bulkButton.prop('disabled', false).html(originalBulkHTML);
                            toggleBulkButton();
                        },
                        error: function(xhr, status, error) {
                            console.error('Error:', error);
                            showAlert('An error occurred while sending QR codes.', 'error');
                            bulkButton.prop('disabled', false).html(originalBulkHTML);
                            $('.rsvp-checkbox:checked').prop('disabled', false);
                            toggleBulkButton();
                        }
                    });
                }
            }
        );
    }

    // Send Birthday QR Code Function
    function sendBirthdayQRcode(rsvpId) {
        const button = $(`button[onclick="sendBirthdayQRcode(${rsvpId})"]`);
        const originalHTML = button.html();
        
        $.ajax({
            url: "{% url 'send_birthday_qr_code' %}",
            type: 'POST',
            data: {
                'rsvp_id': rsvpId,
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            beforeSend: function() {
                button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
            },
            success: function(response) {
                if (response.status === 200) {
                    showAlert('QR code has been sent to the attendee.', 'success');
                    // Update button appearance
                    button.removeClass('btn-primary')
                            .addClass('btn-light text-primary')
                            .prop('disabled', true)
                            .attr('onclick', '')
                            .attr('title', 'Birthday QR Code Sent')
                            .html('<i class="fas fa-circle-check"></i>');
                } else {
                    showAlert(response.message || 'Failed to send QR code.', 'error');
                    button.prop('disabled', false).html(originalHTML);
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
                showAlert('An error occurred while sending QR code.', 'error');
                button.prop('disabled', false).html(originalHTML);
            }
        });
    }

    // Send Birthday Bulk QR Codes Function
    function sendBulkBirthdayQRCodes() {
        const selectedRsvps = $('.rsvp-checkbox:checked').map(function() {
            return $(this).val();
        }).get();

        if (selectedRsvps.length === 0) {
            showAlert('Please select at least one RSVP attendee.', 'warning');
            return;
        }

        showConfirm(
            'Send Bulk QR Codes',
            `Are you sure you want to send Birthday QR codes to ${selectedRsvps.length} attendee(s)?`,
            function(confirmed) {
                if (confirmed) {
                    const bulkButton = $('button[onclick="sendBulkBirthdayQRCodes()"]');
                    const originalBulkHTML = bulkButton.html();
                    
                    $.ajax({
                        url: "{% url 'send_bulk_birthday_qr_codes' %}",
                        type: 'POST',
                        headers: {
                            'X-CSRFToken': '{{ csrf_token }}',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            'rsvp_ids': selectedRsvps
                        }),
                        beforeSend: function() {
                            bulkButton.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Sending...');
                            // Disable all selected checkboxes
                            $('.rsvp-checkbox:checked').prop('disabled', true);
                        },
                        success: function(response) {
                            if (response.status === 200) {
                                showAlert(`Birthday QR codes sent to ${response.sent_count} attendee(s).`, 'success');
                                
                                // Update buttons for successfully sent RSVPs
                                selectedRsvps.forEach(rsvpId => {
                                    const btn = $(`button[onclick="sendBirthdayQRcode(${rsvpId})"]`);
                                    if (btn.length) {
                                        btn.removeClass('btn-primary')
                                        .addClass('btn-light text-primary')
                                        .prop('disabled', true)
                                        .attr('onclick', '')
                                        .attr('title', 'Birthday QR Code Sent')
                                        .html('<i class="fas fa-circle-check"></i>');
                                    }
                                });
                                
                                // Reset checkboxes
                                $('.rsvp-checkbox').prop('checked', false).prop('disabled', false);
                                $('#selectAll').prop('checked', false);
                            } else {
                                showAlert(response.message || 'Failed to send QR codes.', 'error');
                                $('.rsvp-checkbox:checked').prop('disabled', false);
                            }
                            
                            bulkButton.prop('disabled', false).html(originalBulkHTML);
                            toggleBulkButton();
                        },
                        error: function(xhr, status, error) {
                            console.error('Error:', error);
                            showAlert('An error occurred while sending QR codes.', 'error');
                            bulkButton.prop('disabled', false).html(originalBulkHTML);
                            $('.rsvp-checkbox:checked').prop('disabled', false);
                            toggleBulkButton();
                        }
                    });
                }
            }
        );
    }

    // Delete Guest Function
    function deleteGuest(guestId) {
        showConfirm(
            'Delete Guest',
            'Are you sure you want to delete this guest? This action cannot be undone.',
            function(confirmed) {
                if (confirmed) {
                    $.ajax({
                        url: `/delete-rsvp/${guestId}/`,
                        method: 'DELETE',
                        headers: {
                            'X-CSRFToken': '{{ csrf_token }}'
                        },
                        success: function(data) {
                            if (data.success) {
                                showAlert(data.message, 'success');
                                setTimeout(() => {
                                    location.reload();
                                }, 1500);
                            } else {
                                showAlert(data.message, 'error');
                            }
                        },
                        error: function(error) {
                            console.error('Error:', error);
                            showAlert('An error occurred while deleting the guest.', 'error');
                        }
                    });
                }
            }
        );
    }

    // Edit Guest Function
    function editGuest(guestId) {
        const row = $(`tr[data-guest-id="${guestId}"]`);
        const fullName = row.find('td:nth-child(2)').text().trim();
        const nameParts = fullName.split(' ');
        
        const guest = {
            id: guestId,
            first_name: nameParts[0] || '',
            last_name: nameParts.slice(1).join(' ') || '',
            email: row.find('td:nth-child(3)').text().trim(),
            phone: row.find('td:nth-child(4)').text().trim(),
            spouse: row.find('td:nth-child(5)').text().trim(),
            //selected_experiences: row.find('td:nth-child(6)').text().trim().split(', ')
        };

        // Populate modal fields
        $('#editGuestId').val(guest.id);
        $('#editFirstName').val(guest.first_name);
        $('#editLastName').val(guest.last_name);
        $('#editEmail').val(guest.email);
        $('#editPhone').val(guest.phone);
        $('#editSpouse').val(guest.spouse);
        //$('#editExperiences').val(guest.selected_experiences.join(', '));

        // Show the modal
        $('#editModal').modal('show');
    }

    // Handle save changes button click
    $('#saveChangesBtn').on('click', function() {
        const guestId = $('#editGuestId').val();
        const guest = {
            id: guestId,
            first_name: $('#editFirstName').val(),
            last_name: $('#editLastName').val(),
            email: $('#editEmail').val(),
            phone: $('#editPhone').val(),
            spouse: $('#editSpouse').val(),
            //selected_experiences: $('#editExperiences').val().split(',').map(item => item.trim())
        };

        if (guest.first_name && guest.email && guest.phone) {
            $.ajax({
                url: `/edit-rsvp/${guestId}/`,
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                data: JSON.stringify(guest),
                contentType: 'application/json',
                beforeSend: function() {
                    $('#saveChangesBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
                },
                success: function(data) {
                    if (data.success) {
                        showAlert(data.message, 'success');
                        $('#editModal').modal('hide');
                        setTimeout(() => {
                            location.reload();
                        }, 1500);
                    } else {
                        showAlert(data.message, 'error');
                        $('#saveChangesBtn').prop('disabled', false).html('Save changes');
                    }
                },
                error: function(error) {
                    console.error('Error:', error);
                    showAlert('An error occurred while updating the guest.', 'error');
                    $('#saveChangesBtn').prop('disabled', false).html('Save changes');
                }
            });
        } else {
            showAlert('First name, email, and phone are required.', 'error');
        }
    });

    // Handle select all checkbox
    $('#selectAll').on('change', function() {
        $('.rsvp-checkbox').prop('checked', $(this).prop('checked'));
        toggleBulkButton();
    });

    // Handle individual checkboxes
    $(document).on('change', '.rsvp-checkbox', function() {
        const allChecked = $('.rsvp-checkbox').length === $('.rsvp-checkbox:checked').length;
        $('#selectAll').prop('checked', allChecked);
        toggleBulkButton();
    });

    function toggleBulkButton() {
        const checkedBoxes = $('.rsvp-checkbox:checked');
        const bulkThanksgivingButton = $('button[onclick="sendBulkThanksgivingQRCodes()"]');
        const bulkBirthdayButton = $('button[onclick="sendBulkBirthdayQRCodes()"]');
        bulkThanksgivingButton.prop('disabled', checkedBoxes.length === 0);
        bulkBirthdayButton.prop('disabled', checkedBoxes.length === 0);
    }
</script>

{% endblock %}