@extends('layouts.app')

@section('title', 'Event Create')

@section('content')
    <form id="editEventForm" method="POST" action="{{ route('event.update', $event->id) }}">
        @csrf
        @method('PUT')
        <div class="page-header">
            <div class="page-header-left d-flex align-items-center">
                <div class="page-header-title">
                    <h5 class="m-b-10">Event</h5>
                </div>
                <ul class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('index') }}">Home</a></li>
                    <li class="breadcrumb-item">Create</li>
                </ul>
            </div>
            <div class="page-header-right ms-auto">
                <div class="page-header-right-items">
                    <div class="d-flex d-md-none">
                        <a href="javascript:void(0)" class="page-header-right-close-toggle">
                            <i class="feather-arrow-left me-2"></i>
                            <span>Back</span>
                        </a>
                    </div>
                    <div class="d-flex align-items-center gap-2 page-header-right-items-wrapper">
                        <a href="javascript:void(0);" class="btn btn-light-brand successAlertMessage">
                            <i class="feather-layers me-2"></i>
                            <span>Save as Draft</span>
                        </a>
                        <a href="javascript:void(0);" class="btn btn-primary successAlertMessage"
                            onclick="document.getElementById('editEventForm').submit();">
                            <i class="feather-user-plus me-2"></i>
                            <span>Edit Event</span>
                        </a>
                    </div>
                </div>
                <div class="d-md-none d-flex align-items-center">
                    <a href="javascript:void(0)" class="page-header-right-open-toggle">
                        <i class="feather-align-right fs-20"></i>
                    </a>
                </div>
            </div>
        </div>
        <!-- [ page-header ] end -->
        <!-- [ Main Content ] start -->
        <div class="main-content">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card border-top-0">

                        <div class="tab-content">
                            <div class="tab-pane fade show active" id="profileTab" role="tabpanel">
                                <div class="card-body personal-info">
                                    <div class="mb-4 d-flex align-items-center justify-content-between">
                                        <h5 class="fw-bold mb-0 me-4">
                                            <span class="d-block mb-2">Event Information:</span>
                                        </h5>
                                    </div>


                                    <div class="row">


                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Ticket:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-file-text"></i></div>
                                                    <select class="form-control" name="ticket_id" id="ticket-dropdown">
                                                        <option value="">Select Ticket</option>
                                                        @foreach ($tickets as $ticket)
                                                            <option value="{{ $ticket->id }}"
                                                                {{ $event->ticket_id == $ticket->id ? 'selected' : '' }}>
                                                                {{ $ticket->topic }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="topicInput" class="fw-semibold">Topic:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-message-square"></i>
                                                    </div>
                                                    <input type="text" class="form-control" name="topic"
                                                        id="topicInput" placeholder="Topic"
                                                        value="{{ old('topic', $event->topic) }}">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Category:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="category" id="category-dropdown">
                                                    <option value="">Select Category</option>
                                                    <option value="Meeting"
                                                        {{ $event->category == 'Meeting' ? 'selected' : '' }}>Meeting
                                                    </option>
                                                    <option value="Memo"
                                                        {{ $event->category == 'Memo' ? 'selected' : '' }}>Memo</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="contactNameInput" class="fw-semibold">Contact Name:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-phone"></i></div>
                                                    <input type="text" class="form-control" name="contact_name"
                                                        id="contactNameInput" placeholder="Contact Name"
                                                        value="{{ old('contact_name', $event->contact_name) }}" required>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Status:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-clipboard"></i></div>
                                                    <select class="form-control" name="status" id="status-dropdown">
                                                        <option value="">Select Status</option>
                                                        <option value="New"
                                                            {{ $event->status == 'New' ? 'selected' : '' }}>New</option>
                                                        <option value="In Progress"
                                                            {{ $event->status == 'In Progress' ? 'selected' : '' }}>In
                                                            Progress</option>
                                                        <option value="On Hold"
                                                            {{ $event->status == 'On Hold' ? 'selected' : '' }}>On Hold
                                                        </option>
                                                        <option value="Completed"
                                                            {{ $event->status == 'Completed' ? 'selected' : '' }}>Completed
                                                        </option>
                                                        <option value="Cancelled"
                                                            {{ $event->status == 'Cancelled' ? 'selected' : '' }}>Cancelled
                                                        </option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Due Date & Time:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                                    <input type="datetime-local" class="form-control"
                                                        name="due_date_time" id="due-date-time"
                                                        value="{{ old('due_date_time', $event->due_date_time) }}">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Priority: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="priority_id">
                                                    <option value="">Select Priority</option>
                                                    @foreach ($priorities as $priority)
                                                        <option value="{{ $priority->id }}"
                                                            {{ $event->priority == $priority->id ? 'selected' : '' }}>
                                                            {{ $priority->name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Event Owner: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="contact_owner"
                                                    id="contact-owner-dropdown">
                                                    @foreach ($users as $user)
                                                        <option value="{{ $user->id }}"
                                                            {{ $event->contact_owner == $user->id ? 'selected' : '' }}>
                                                            {{ $user->name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Reminder Status:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="reminder_status"
                                                    id="reminder-status-dropdown">
                                                    <option value="">Select Reminder Status</option>
                                                    <option value="Popup"
                                                        {{ $event->reminder_status == 'Popup' ? 'selected' : '' }}>Popup
                                                    </option>
                                                    <option value="Email"
                                                        {{ $event->reminder_status == 'Email' ? 'selected' : '' }}>Email
                                                    </option>
                                                    <option value="SMS"
                                                        {{ $event->reminder_status == 'SMS' ? 'selected' : '' }}>SMS
                                                    </option>
                                                    <option value="Time"
                                                        {{ $event->reminder_status == 'Time' ? 'selected' : '' }}>Time
                                                    </option>
                                                    <option value="Hours"
                                                        {{ $event->reminder_status == 'Hours' ? 'selected' : '' }}>Hours
                                                    </option>
                                                    <option value="Minutes"
                                                        {{ $event->reminder_status == 'Minutes' ? 'selected' : '' }}>
                                                        Minutes</option>
                                                    <option value="Days"
                                                        {{ $event->reminder_status == 'Days' ? 'selected' : '' }}>Days
                                                    </option>
                                                </select>
                                            </div>
                                        </div>


                                    </div>

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


@endsection

@section('scripts')
    <script>
        function addPhoneField() {
            const newPhoneRow = `
        <div class="row align-items-center mb-2 phone-row">
            <div class="col-md-12">
                <div class="input-group">
                    <div class="input-group-text">
                        <i class="feather-phone"></i>
                    </div>
                    <select class="form-control" style="width: 120px !important; min-width: 120px !important; max-width: 80px !important; padding-left: 10 !important; display: inline-block;" name="phone_types[]">
                        <option value="1">Mobile</option>
                        <option value="2">Home</option>
                        <option value="3">Work</option>
                        <option value="4">Other</option>
                    </select>
                    <input type="text" name="phones[]" class="form-control" placeholder="Phone Number">
                    <button type="button" class="btn btn-danger" onclick="removePhoneField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#phoneContainer .col-lg-12").insertAdjacentHTML('beforeend', newPhoneRow);
        }

        function removePhoneField(button) {
            button.closest(".phone-row").remove();
        }

        function addEmailField() {
            const newEmailRow = `
        <div class="row align-items-center mb-2 email-row">
            <div class="col-md-12">
                <div class="input-group">
                    <div class="input-group-text">
                        <i class="feather-mail"></i>
                    </div>
                    <select class="form-control" style="width: 120px !important; min-width: 120px !important; max-width: 80px !important; padding-left: 10 !important; display: inline-block;" name="email_types[]">
                        <option value="1">Personal</option>
                        <option value="2">Work</option>
                        <option value="3">Other</option>
                    </select>
                    <input type="email" name="emails[]" class="form-control" placeholder="Email Address">
                    <button type="button" class="btn btn-danger" onclick="removeEmailField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#emailContainer .col-lg-12").insertAdjacentHTML('beforeend', newEmailRow);
        }

        function removeEmailField(button) {
            button.closest(".email-row").remove();
        }


        function addSocialMediaField() {
            const newSocialMediaRow = `
        <div class="row align-items-center mb-2 social-media-row">
            <div class="col-md-12">
                <div class="input-group">
                    <!-- Default Social Media Icon -->
                    <div class="input-group-text">
                        <i class="feather-facebook" id="icon-facebook"></i>
                    </div>
                    <!-- Social Media Type -->
                    <select class="form-control" style="width: 120px !important; min-width: 120px !important; max-width: 80px !important; padding-left: 10 !important; display: inline-block;" name="social_media_types[]" onchange="changeSocialMediaIcon(this)">
                        <option data-id="1" value="facebook">Facebook</option>
                        <option data-id="2" value="twitter">Twitter</option>
                        <option data-id="3" value="linkedin">LinkedIn</option>
                        <option data-id="4" value="instagram">Instagram</option>
                        <option data-id="5" value="other">Other</option>
                    </select>
                    <!-- Social Media Input -->
                    <input type="text" class="form-control" name="social_media_values[]" placeholder="Social Media URL">
                    <!-- Remove Button -->
                    <button type="button" class="btn btn-danger" onclick="removeSocialMediaField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#socialMediaContainer .col-lg-12").insertAdjacentHTML('beforeend', newSocialMediaRow);
        }

        function removeSocialMediaField(button) {
            button.closest(".social-media-row").remove();
        }

        function changeSocialMediaIcon(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const selectedId = selectedOption.getAttribute('data-id'); // Get the id of the selected social media
            const iconElement = selectElement.closest('.input-group').querySelector('.input-group-text i');

            // Change the icon based on the selected id
            switch (selectedId) {
                case "1":
                    iconElement.className = "feather-facebook";
                    break;
                case "2":
                    iconElement.className = "feather-twitter";
                    break;
                case "3":
                    iconElement.className = "feather-linkedin";
                    break;
                case "4":
                    iconElement.className = "feather-instagram";
                    break;
                default:
                    iconElement.className = "feather-globe"; // Default icon for 'other'
                    break;
            }
        }

        document.querySelectorAll('.dropdown-item').forEach(function(item) {
            item.addEventListener('click', function(e) {
                e.preventDefault();

                var rating = this.getAttribute('data-value');
                var ratingText = this.innerHTML.trim();

                document.getElementById('ratingDropdown').innerHTML = ratingText + '';

                document.getElementById('ratingInput').value = rating;

                document.getElementById('ratingDropdown').classList.add('border-primary');
                document.getElementById('ratingDropdown').classList.remove('border-primary');
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            $('#primary-contact-dropdown').select2({
                placeholder: "Select Contact",
                minimumResultsForSearch: 0,
                width: 'resolve'
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            $('#lead-source-dropdown').select2({
                placeholder: "Select Lead Source",
                minimumResultsForSearch: 0,
                width: 'resolve'
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            $('#contact-owner-dropdown').select2({
                placeholder: "Select Owner",
                minimumResultsForSearch: 0,
                width: 'resolve'
            });
        });
    </script>

    <script>
        function openAddCompanyModal() {
            const addCompanyModal = new bootstrap.Modal(document.getElementById('addCompanyModal'));
            addCompanyModal.show();
        }

        function saveNewCompany() {
            const companyName = document.getElementById('newCompanyName').value.trim();

            if (companyName) {
                // Perform an AJAX request to save the company to the backend
                fetch("{{ route('companies.store') }}", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        },
                        body: JSON.stringify({
                            name: companyName
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Add the new company to the dropdown
                            const companyDropdown = document.getElementById('company-dropdown');
                            const newOption = document.createElement('option');
                            newOption.text = data.data.name; // Use the company name from the response
                            newOption.value = data.data.id; // Use the company ID from the response
                            newOption.selected = true; // Select the new company by default
                            companyDropdown.add(newOption);

                            // Close the modal
                            const addCompanyModal = bootstrap.Modal.getInstance(document.getElementById(
                                'addCompanyModal'));
                            addCompanyModal.hide();

                            // Clear the input field for next use
                            document.getElementById('newCompanyName').value = '';
                        } else {
                            alert('Failed to add company. Please try again.');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('An error occurred. Please try again.');
                    });
            } else {
                alert('Please enter a valid company name.');
            }
        }
    </script>

@endsection
