@extends('layouts.app')

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

@section('content')
    <!-- [ page-header ] start -->
    <form id="createContactForm" method="POST" action="/contacts/store" enctype="multipart/form-data">
    @csrf
    @if (!empty($ticketId))
        <input type="hidden" name="source_ticket_id" value="{{ $ticketId }}">
    @endif
        <div class="page-header">
            <div class="page-header-left d-flex align-items-center">
                <div class="page-header-title">
                    <h5 class="m-b-10">Contact</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('createContactForm').submit();">
                            <i class="feather-user-plus me-2"></i>
                            <span>Create Contact</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">Contact 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">Contact 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>
                                            </div>
                                            @error('contact_owner')
                                                <small class="text-danger">{{ $message }}</small>
                                            @enderror
                                        </div>




                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Lead Source: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="lead_source"
                                                    id="lead-source-dropdown">
                                                    <option value="">Select Lead Source</option>
                                                    <option value="2">Social Media</option>
                                                    <option value="3">Referral</option>
                                                    <option value="4">Email Campaign</option>
                                                    <option value="5">Cold Call</option>
                                                    <option value="6">Trade Show</option>
                                                    <option value="7">Website</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4  align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="fullnameInput" class="fw-semibold">First Name:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-user"></i>
                                                    </div>
                                                    <input type="text" class="form-control"
                                                        name="first_name" id="fullnameInput"
                                                        placeholder="First Name">
                                                </div>
                                                @error('first_name')
                                                    <small class="text-danger">{{ $message }}</small>
                                                @enderror
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4  align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="fullnameInput" class="fw-semibold">Last Name:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-user"></i>
                                                    </div>
                                                    <input type="text" class="form-control"
                                                        name="last_name" id="fullnameInput"
                                                        placeholder="Last Name">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 align-items-center col-md-6">
                                            <div class="col-lg-4 mb-2"><label class="fw-semibold">Accounts:</label></div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="account_ids[]" multiple data-select2-selector="tag">
                                                    @foreach ($accounts as $account)
                                                        <option value="{{ $account->id }}" @selected(in_array($account->id, old('account_ids', [])))>
                                                            {{ $account->account_name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                <small class="text-muted">Select one or more Accounts.</small>
                                            </div>
                                        </div>

                                        <div class=" mb-4 align-items-center col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Company Name: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-home"></i></div>
                                                    <select class="form-control" name="company_id" id="company-dropdown">
                                                        <option value="">Select Company</option>
                                                        @foreach ($companies as $company)
                                                            <option value="{{ $company->id }}">
                                                                {{ $company->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                    <button type="button" class="btn btn-primary" onclick="openAddCompanyModal()">
                                                        <i class="feather-plus"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>

                                        <div class=" mb-4 align-items-center col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="jobTitleInput" class="fw-semibold">Job Title:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-briefcase"></i>
                                                    </div>
                                                    <input type="text" class="form-control"
                                                        name="job_title" id="jobTitleInput"
                                                        placeholder="Job Title">
                                                </div>
                                            </div>
                                        </div>

                                        <div id="phoneContainer" class=" mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="phoneInput" class="fw-semibold">Phone: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <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-primary"
                                                                onclick="addPhoneField()">
                                                                <i class="feather-plus"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div id="emailContainer" class=" mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="mailInput" class="fw-semibold">Email: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <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-primary"
                                                                onclick="addEmailField()">
                                                                <i class="feather-plus"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>


                                        <div class=" mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="departmentInput" class="fw-semibold">Department:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <!-- Department Icon -->
                                                    <div class="input-group-text"><i
                                                            class="feather-layers"></i>
                                                    </div>
                                                    <!-- Department Input -->
                                                    <input type="text" class="form-control"
                                                        name="department" id="departmentInput"
                                                        placeholder="Department">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="genderInput" class="fw-semibold">Gender: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-user"></i>
                                                    </div>
                                                    <select class="form-control" id="genderInput"
                                                        name="gender">
                                                        <option value="male">Male</option>
                                                        <option value="female">Female</option>
                                                        <option value="other">Other</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="dateofBirth" class="fw-semibold">Date of Birth:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-calendar"></i>
                                                    </div>
                                                    <input type="date" class="form-control" name="dateofbirth"
                                                        id="dateofBirth" value="{{ date('Y-m-d') }}">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="addressInput_2" class="fw-semibold">Address 1:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-map-pin"></i>
                                                    </div>
                                                    <textarea class="form-control" name="address1" id="addressInput_2" cols="30" rows="3"
                                                        placeholder="Address"></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="addressInput_2" class="fw-semibold">Address 2:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-map-pin"></i>
                                                    </div>
                                                    <textarea class="form-control" name="address2" id="addressInput_2" cols="30" rows="3"
                                                        placeholder="Address"></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="zipCodeInput" class="fw-semibold">Zip Code:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-tag"></i>
                                                    </div>
                                                    <input type="number" name="zipcode" class="form-control"
                                                        id="zipCodeInput" placeholder="Zip Code">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="cityInput" class="fw-semibold">City: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-map-pin"></i></div>
                                                    <input type="text" name="city" class="form-control"
                                                        id="cityInput" placeholder="Enter City">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="provinceInput" class="fw-semibold">Province:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-map"></i>
                                                    </div>
                                                    <input type="text" name="province"
                                                        class="form-control" id="provinceInput"
                                                        placeholder="Enter Province">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Country: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="country_id"
                                                    data-select2-selector="country">
                                                    <option value="">Select Country</option>
                                                    @foreach ($countries as $country)
                                                        <option value="{{ $country->id }}"
                                                            data-country="{{ strtolower($country->code) }}">
                                                            {{ $country->name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div id="socialMediaContainer" class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="socialMediaInput" class="fw-semibold">Social
                                                    Media:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <!-- Initial Social Media Row -->
                                                <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)">
                                                                @foreach ($socialMedias as $socialMedia)
                                                                    <option value="{{ $socialMedia->name }}"
                                                                        data-id="{{ $socialMedia->id }}">
                                                                        {{ ucfirst($socialMedia->name) }}
                                                                    </option>
                                                                @endforeach
                                                            </select>

                                                            <!-- Social Media Input -->
                                                            <input type="text" name="social_media_values[]"
                                                                class="form-control"
                                                                placeholder="Social Media URL">
                                                            <!-- Add Button -->
                                                            <button type="button" class="btn btn-primary"
                                                                onclick="addSocialMediaField()">
                                                                <i class="feather-plus"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Languages: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="languages[]" multiple
                                                    data-select2-selector="language">
                                                    @foreach ($languages as $language)
                                                        <option value="{{ $language->id }}"
                                                            data-language="bg-primary">{{ $language->name }}
                                                        </option>
                                                    @endforeach
                                                </select>

                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Stage: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="stage_id" id="stageDropdown"
                                                    data-select2-selector="stage">
                                                    <option value="1" data-stage="bg-primary" selected>New
                                                    </option>
                                                    <option value="2" data-stage="bg-secondary">In
                                                        Progress
                                                    </option>
                                                    <option value="3" data-stage="bg-success">Completed
                                                    </option>
                                                    <option value="4" data-stage="bg-warning">On Hold
                                                    </option>
                                                    <option value="5" data-stage="bg-danger">Cancelled
                                                    </option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Type: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="type" required>
                                                    <option value="">Select Type</option>
                                                    <option value="customer" @selected(old('type') === 'customer')>Customer</option>
                                                    <option value="vendor" @selected(old('type') === 'vendor')>Vendor</option>
                                                    <option value="partner" @selected(old('type') === 'partner')>Partner</option>
                                                    <option value="agent" @selected(old('type') === 'agent')>Agent</option>
                                                </select>
                                                @error('type')
                                                    <div class="text-danger mt-2">{{ $message }}</div>
                                                @enderror
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <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" required>
                                                    <option value="">Select Priority</option>
                                                    <option value="high" @selected(old('priority') === 'high')>High</option>
                                                    <option value="medium" @selected(old('priority') === 'medium')>Medium</option>
                                                    <option value="low" @selected(old('priority') === 'low')>Low</option>
                                                </select>
                                                @error('priority')
                                                    <div class="text-danger mt-2">{{ $message }}</div>
                                                @enderror
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="aboutInput" class="fw-semibold">About: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-type"></i>
                                                    </div>
                                                    <textarea class="form-control" name="about" id="aboutInput" cols="30" rows="5" placeholder="About"></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Status: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="status"
                                                    data-select2-selector="status">
                                                    <option value="active" data-bg="bg-success" selected>
                                                        Active
                                                    </option>
                                                    <option value="inactive" data-bg="bg-warning">Inactive
                                                    </option>
                                                    <option value="archived" data-bg="bg-danger">Declined
                                                    </option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Avatar / Attachment: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <input type="file" name="avatar" class="form-control">
                                                <small class="text-muted">Upload an avatar or file.</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </div>
    </form>
    <!-- [ Main Content ] end -->
@endsection

<style>
    .input-group .select2-container {
        flex: 1;
    }
</style>

@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; 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; 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 to add a new Social Media row
        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; display: inline-block;" name="social_media_types[]" onchange="changeSocialMediaIcon(this)">
                        @foreach ($socialMedias as $socialMedia)
                            <option value="{{ $socialMedia->name }}" data-id="{{ $socialMedia->id }}">
                                {{ ucfirst($socialMedia->name) }}
                            </option>
                        @endforeach
                    </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 to remove a Social Media row
        function removeSocialMediaField(button) {
            button.closest(".social-media-row").remove();
        }

        function changeSocialMediaIcon(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            let selectedId = null;
            let textValue = null;
            if(selectedOption) {
                selectedId = selectedOption.getAttribute('data-id'); 
                textValue = selectedOption.value.toLowerCase();
            }
            const iconElement = selectElement.closest('.input-group').querySelector('.input-group-text i');

            // Change the icon based on the selected value
            if (textValue === 'facebook') iconElement.className = "feather-facebook";
            else if (textValue === 'twitter') iconElement.className = "feather-twitter";
            else if (textValue === 'linkedin') iconElement.className = "feather-linkedin";
            else if (textValue === 'instagram') iconElement.className = "feather-instagram";
            else if (textValue === 'youtube') iconElement.className = "feather-youtube";
            else iconElement.className = "feather-link"; // Default icon for 'other'
        }
    </script>

    <script>
        $(document).ready(function() {
            $('#contact-owner-dropdown').select2({
                placeholder: "Select Owner",
                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() {
            function formatCountry(country) {
                if (!country.id) { return country.text; }
                var countryCode = $(country.element).data('country');
                if (!countryCode) { return country.text; }
                var $country = $(
                    '<span><img src="/assets/vendors/img/flags/1x1/' + countryCode + '.svg" style="width: 20px; height: 15px; margin-right: 8px; object-fit: cover;" /> ' + country.text + '</span>'
                );
                return $country;
            }

            $('[data-select2-selector="country"]').select2({ 
                placeholder: "Select Country",
                templateResult: formatCountry,
                templateSelection: formatCountry
            });

            $('[data-select2-selector="language"]').select2({ placeholder: "Select Language" });
            $('[data-select2-selector="stage"]').select2({ placeholder: "Select Stage" });
            $('[data-select2-selector="status"]').select2({ placeholder: "Select Status" });
            
            $('#company-dropdown').select2({
                placeholder: "Select Company",
                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
