@extends('layouts.app')

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

@section('content')
    <form id="createTaskForm" method="POST" action="/tasks/store">
        @csrf
        <div class="page-header">
            <div class="page-header-left d-flex align-items-center">
                <div class="page-header-title">
                    <h5 class="m-b-10">Task</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('createTaskForm').submit();">
                            <i class="feather-user-plus me-2"></i>
                            <span>Add Task</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="card-header p-0">
                                <!-- Nav tabs -->
                                <ul class="nav nav-tabs flex-wrap w-100 text-center customers-nav-tabs" id="myTab"
                                    role="tablist">
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link active" data-bs-toggle="tab"
                                            data-bs-target="#profileTab" role="tab">Profile</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#passwordTab" role="tab">Password</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#billingTab" role="tab">Billing & Shipping</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#subscriptionTab" role="tab">Subscription</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#notificationsTab" role="tab">Notifications</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#connectionTab" role="tab">Connection</a>
                                    </li>
                                </ul>
                            </div> --}}


                        <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">Task Information:</span>
                                        </h5>
                                    </div>
                                    {{-- <div class="row mb-4 align-items-center">
                                                <div class="col-lg-4">
                                                    <label class="fw-semibold">Avatar: </label>
                                                </div>
                                                <div class="col-lg-8">
                                                    <div class="mb-4 mb-md-0 d-flex gap-4 your-brand">
                                                        <div
                                                            class="wd-100 ht-100 position-relative overflow-hidden border border-gray-2 rounded">
                                                            <img src="assets/images/avatar/1.png"
                                                                class="upload-pic img-fluid rounded h-100 w-100"
                                                                alt="">
                                                            <div
                                                                class="position-absolute start-50 top-50 end-0 bottom-0 translate-middle h-100 w-100 hstack align-items-center justify-content-center c-pointer upload-button">
                                                                <i class="feather feather-camera"
                                                                    aria-hidden="true"></i>
                                                            </div>
                                                            <input class="file-upload" type="file" accept="image/*">
                                                        </div>
                                                        <div class="d-flex flex-column gap-1">
                                                            <div class="fs-11 text-gray-500 mt-2"># Upload your prifile
                                                            </div>
                                                            <div class="fs-11 text-gray-500"># Avatar size 150x150</div>
                                                            <div class="fs-11 text-gray-500"># Max upload size 2mb</div>
                                                            <div class="fs-11 text-gray-500"># Allowed file types: png,
                                                                jpg, jpeg</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div> --}}

                                    <div class="row">
                                        {{-- @php
                                            $selectedContactId = request('id');
                                        @endphp

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Contact: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="primary_contact"
                                                    id="primary-contact-dropdown"
                                                    {{ $selectedContactId ? 'disabled' : '' }}>
                                                    <option value="" disabled
                                                        {{ !$selectedContactId ? 'selected' : '' }}>Select
                                                        Contact</option>
                                                    @foreach ($contacts as $contact)
                                                        <option value="{{ $contact->id }}"
                                                            {{ $selectedContactId == $contact->id ? 'selected' : '' }}>
                                                            {{ $contact->first_name }}
                                                        </option>
                                                    @endforeach
                                                </select>

                                                @if ($selectedContactId)
                                                    <input type="hidden" name="primary_contact"
                                                        value="{{ $selectedContactId }}">

                                                @endif
                                            </div>
                                        </div> --}}






                                        <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 }}">
                                                                {{ $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">
                                                </div>
                                            </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" 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">New</option>
                                                        <option value="In Progress">In Progress</option>
                                                        <option value="On Hold">On Hold</option>
                                                        <option value="Completed">Completed</option>
                                                        <option value="Cancelled">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">
                                                </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"
                                                    data-select2-selector="language">
                                                    <option value="">Select Priority</option>
                                                    @foreach ($priorities as $priority)
                                                        <option value="{{ $priority->id }}" data-language="bg-primary">
                                                            {{ $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">Task 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 }}"
                                                            {{ auth()->id() == $user->id ? 'selected' : '' }}>
                                                            {{ $user->name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                <!-- Hidden input to send the ID when the form is submitted -->
                                                <input type="hidden" name="contact_owner" value="{{ auth()->id() }}">
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="descriptionInput" class="fw-semibold">Description:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-file-text"></i></div>
                                                    <textarea class="form-control" name="description" id="descriptionInput" cols="30" rows="3"
                                                        placeholder="Enter description"></textarea>
                                                </div>
                                            </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">Popup</option>
                                                    <option value="Email">Email</option>
                                                    <option value="SMS">SMS</option>
                                                    <option value="Time">Time</option>
                                                    <option value="Hours">Hours</option>
                                                    <option value="Minutes">Minutes</option>
                                                    <option value="Days">Days</option>
                                                </select>
                                            </div>
                                        </div>


                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row px-4 pb-4"><div class="col-lg-12"><label class="form-label">Additional Assigned Employees</label>
            <select class="form-control" name="assignee_ids[]" multiple>@foreach($users as $user)<option value="{{ $user->id }}">{{ $user->name }}</option>@endforeach</select>
        </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
