@extends('layouts.app')

@section('title', 'Lead Edit')

@section('content')
    @include('leads.partials.contact-method-multiselect-style')
    <style>
        .lead-edit-page { padding-top: 20px; }
        .lead-edit-card { border: 1px solid #e5e9f0 !important; border-radius: 15px !important; box-shadow: 0 9px 30px rgba(15, 23, 42, .055) !important; overflow: hidden; }
        .lead-edit-intro { display: flex; align-items: center; gap: 14px; padding: 20px 22px; border-bottom: 1px solid #e8ebf0; background: linear-gradient(135deg, #fff 0%, #f7f9ff 100%); }
        .lead-edit-intro-icon { display: inline-flex; width: 46px; height: 46px; flex: 0 0 auto; align-items: center; justify-content: center; border-radius: 13px; background: #3454d1; color: #fff; font-size: 18px; box-shadow: 0 7px 16px rgba(52, 84, 209, .2); }
        .lead-edit-grid > [class*="col-"] { margin-bottom: 18px !important; }
        .lead-edit-section { width: 100%; margin: 8px 0 2px !important; padding-top: 18px; border-top: 1px solid #edf0f4; }
        .lead-edit-section:first-child { margin-top: 0 !important; padding-top: 0; border-top: 0; }
        .lead-edit-section-title { display: flex; align-items: center; gap: 9px; margin-bottom: 3px; color: #253047; font-size: 13px; font-weight: 750; }
        .lead-edit-section-title i { display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center; border-radius: 8px; background: #eef2ff; color: #3454d1; }
        .lead-edit-section small { margin-left: 37px; color: #8792a2; }
        .lead-edit-actions { position: sticky; bottom: 0; z-index: 5; display: flex; justify-content: flex-end; gap: 9px; padding: 15px 22px; border-top: 1px solid #e5e9f0; background: rgba(255,255,255,.96); backdrop-filter: blur(8px); }
        .lead-edit-page #phoneContainer .input-group,
        .lead-edit-page #emailContainer .input-group,
        .lead-edit-page #socialMediaContainer .input-group { flex-wrap: nowrap; }
        .lead-edit-page #phoneContainer select,
        .lead-edit-page #emailContainer select,
        .lead-edit-page #socialMediaContainer select { width: 108px !important; min-width: 108px !important; max-width: 108px !important; flex: 0 0 108px !important; }
        .lead-edit-page #phoneContainer input,
        .lead-edit-page #emailContainer input,
        .lead-edit-page #socialMediaContainer input { min-width: 0; }
        .lead-edit-page .lead-edit-icon-field > .select2-container { flex: 1 1 auto; width: 1% !important; min-width: 0; }
        .lead-edit-page .lead-edit-icon-field > .form-control,
        .lead-edit-page .lead-edit-icon-field > .form-select { min-width: 0; }
        .lead-edit-page .lead-edit-icon-field > .input-group-text { width: 42px; justify-content: center; color: #3454d1; background: #f5f7ff; }
        @media (max-width: 767.98px) {
            .lead-edit-page { padding-top: 12px; }
            .lead-edit-card { border-radius: 11px !important; }
            .lead-edit-actions { padding: 12px 16px; }
            .lead-edit-actions .btn { flex: 1 1 0; }
        }
    </style>
    <!-- [ page-header ] start -->
    <form id="updateLeadForm" method="POST" action="{{ route('leads.update', $lead->id) }}">
        @csrf
        @method('PUT')
        <div class="page-header">
            <div class="page-header-left d-flex align-items-center">
                <a href="{{ route('leads.view', ['id' => $lead->id]) }}" class="avatar-text avatar-md me-3" title="Back to Lead" aria-label="Back to Lead"><i class="feather-arrow-left"></i></a>
                <div class="page-header-title">
                    <h5 class="mb-1">Edit Lead</h5>
                    <small class="text-muted d-none d-lg-block">Update {{ $lead->topic ?: 'Lead #'.$lead->id }}</small>
                </div>
            </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="{{ route('leads.view', ['id' => $lead->id]) }}" class="btn btn-light-brand"><i class="feather-x me-2"></i>Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="feather-save me-2"></i>
                            <span>Update Lead</span>
                        </button>
                    </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>
        <div class="main-content lead-edit-page">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card border-top-0 lead-edit-card">

                        <div class="tab-content">
                            <div class="tab-pane fade show active" id="profileTab" role="tabpanel">
                                <div class="lead-edit-intro">
                                    <span class="lead-edit-intro-icon"><i class="feather-edit-3"></i></span>
                                    <div><h5 class="fw-bold mb-1">Edit Lead Information</h5><p class="text-muted mb-0">Keep ownership, contact details and qualification data accurate.</p></div>
                                </div>
                                <div class="card-body personal-info">
                                    <div class="row lead-edit-grid">

                                        <div class="col-12 lead-edit-section">
                                            <div class="lead-edit-section-title"><i class="feather-compass"></i>Lead Assignment</div>
                                            <small>Update the source, owner and purpose of this Lead.</small>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            @php
                                                $contactMethods = old('contact_methods', $lead->contact_method ?? []);
                                                if (is_string($contactMethods)) {
                                                    $contactMethods = json_decode($contactMethods, true) ?: [];
                                                }
                                                $contactMethods = is_array($contactMethods) ? $contactMethods : [];
                                            @endphp
                                            <div class="col-lg-4 mb-2">
                                                <label for="primary-contact-dropdown" class="fw-semibold">Contact:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-contact-search">
                                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                                    <select class="form-control" name="primary_contact"
                                                        id="primary-contact-dropdown" data-lead-contact-search
                                                        data-placeholder="Search and select contact">
                                                        <option value=""></option>
                                                        @foreach ($contacts as $contact)
                                                            <option value="{{ $contact->id }}"
                                                                {{ old('primary_contact', $lead->primary_contact_id) == $contact->id ? 'selected' : '' }}>
                                                                {{ trim($contact->first_name.' '.$contact->last_name) ?: 'Contact #'.$contact->id }}
                                                            </option>
                                                        @endforeach
                                                    </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">Contact Owner <span class="text-danger">*</span></label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-edit-icon-field">
                                                    <div class="input-group-text"><i class="feather-user-check"></i></div>
                                                    <select class="form-control @error('contact_owner') is-invalid @enderror" name="contact_owner"
                                                        id="contact-owner-dropdown" required>
                                                        @foreach ($users as $user)
                                                            <option value="{{ $user->id }}"
                                                                {{ old('contact_owner', $lead->contact_owner_id) == $user->id ? 'selected' : '' }}>
                                                                {{ $user->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                @error('contact_owner')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                            </div>
                                        </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">
                                                <div class="input-group lead-edit-icon-field">
                                                    <div class="input-group-text"><i class="feather-share-2"></i></div>
                                                    <select class="form-control" name="lead_source" id="lead-source-dropdown">
                                                    <option value="1"
                                                        {{ old('lead_source', $lead->lead_source) == 1 ? 'selected' : '' }}>
                                                        Select Lead Source
                                                    </option>
                                                    <option value="2"
                                                        {{ old('lead_source', $lead->lead_source) == 2 ? 'selected' : '' }}>
                                                        Social Media
                                                    </option>
                                                    <option value="3"
                                                        {{ old('lead_source', $lead->lead_source) == 3 ? 'selected' : '' }}>
                                                        Referral
                                                    </option>
                                                    <option value="4"
                                                        {{ old('lead_source', $lead->lead_source) == 4 ? 'selected' : '' }}>
                                                        Email Campaign
                                                    </option>
                                                    <option value="5"
                                                        {{ old('lead_source', $lead->lead_source) == 5 ? 'selected' : '' }}>
                                                        Cold Call
                                                    </option>
                                                    <option value="6"
                                                        {{ old('lead_source', $lead->lead_source) == 6 ? 'selected' : '' }}>
                                                        Trade Show
                                                    </option>
                                                    <option value="7"
                                                        {{ old('lead_source', $lead->lead_source) == 7 ? 'selected' : '' }}>
                                                        Website
                                                    </option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <label class="fw-semibold mb-2">Unqualified Reason:</label>
                                            <div class="input-group lead-edit-icon-field">
                                                <div class="input-group-text"><i class="feather-alert-circle"></i></div>
                                                <textarea class="form-control" name="unqualified_reason" rows="3"
                                                    placeholder="Required when Lead Status is Unqualified">{{ old('unqualified_reason', $lead->unqualified_reason) }}</textarea>
                                            </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 <span class="text-danger">*</span></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 @error('topic') is-invalid @enderror" name="topic"
                                                        id="topicInput" value="{{ old('topic', $lead->topic) }}" placeholder="Topic" required>
                                                </div>
                                                @error('topic')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="qualificationInput" class="fw-semibold">Qualification:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-award"></i></div>
                                                    <input type="text" class="form-control"
                                                        name="qualification" id="qualificationInput" maxlength="255"
                                                        value="{{ old('qualification', $lead->qualification) }}"
                                                        placeholder="e.g. Budget and authority confirmed">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-12 lead-edit-section">
                                            <div class="lead-edit-section-title"><i class="feather-user"></i>Contact Information</div>
                                            <small>Maintain the person, company and direct communication details.</small>
                                        </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"
                                                        value="{{ old('first_name', $lead->first_name) }}" name="first_name"
                                                        id="fullnameInput" placeholder="First Name">
                                                </div>
                                            </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"
                                                        value="{{ $lead->last_name }}" name="last_name"
                                                        id="fullnameInput" placeholder="Last Name">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Company Name: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-edit-icon-field">
                                                    <div class="input-group-text"><i class="feather-briefcase"></i></div>
                                                    <select class="form-control" name="company_id" id="company-dropdown">
                                                        @foreach ($companies as $company)
                                                            <option value="{{ $company->id }}"
                                                                {{ $lead->company_id == $company->id ? 'selected' : '' }}>
                                                                {{ $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="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Industry: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-edit-icon-field">
                                                    <div class="input-group-text"><i class="feather-layers"></i></div>
                                                    <select class="form-control" name="industry_id" id="industry-dropdown">
                                                    <option value=""
                                                        {{ $lead->industry_id == '' ? 'selected' : '' }}>Select
                                                        Industry</option>
                                                    <option value="1"
                                                        {{ $lead->industry_id == 1 ? 'selected' : '' }}>
                                                        Technology
                                                    </option>
                                                    <option value="2"
                                                        {{ $lead->industry_id == 2 ? 'selected' : '' }}>Finance
                                                    </option>
                                                    <option value="3"
                                                        {{ $lead->industry_id == 3 ? 'selected' : '' }}>
                                                        Healthcare
                                                    </option>
                                                    <option value="4"
                                                        {{ $lead->industry_id == 4 ? 'selected' : '' }}>Retail
                                                    </option>
                                                    <option value="5"
                                                        {{ $lead->industry_id == 5 ? 'selected' : '' }}>
                                                        Manufacturing</option>
                                                    <option value="6"
                                                        {{ $lead->industry_id == 6 ? 'selected' : '' }}>Energy
                                                    </option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>



                                        <div class="col-md-6 mb-4 align-items-center">
                                            <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"
                                                        value="{{ $lead->job_title }}" name="job_title"
                                                        id="jobTitleInput" placeholder="Job Title">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <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" value="{{ $lead->zip_code }}" name="zipcode"
                                                        class="form-control" id="zipCodeInput" placeholder="Zip Code">
                                                </div>
                                            </div>
                                        </div>
                                        <div id="phoneContainer" class="col-md-6 mb-4">
                                            <div class="col-lg-4 mb-2">
                                                <label for="phoneInput" class="fw-semibold">Phone Number <span class="text-danger">*</span></label>
                                            </div>
                                            <div class="col-lg-12">
                                                @foreach ($lead->contactPhones as $phone)
                                                    <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-select"
                                                                    name="phone_types[]">
                                                                    <option value="1"
                                                                        {{ $phone->phone_type_id == 1 ? 'selected' : '' }}>
                                                                        Mobile</option>
                                                                    <option value="2"
                                                                        {{ $phone->phone_type_id == 2 ? 'selected' : '' }}>
                                                                        Home</option>
                                                                    <option value="3"
                                                                        {{ $phone->phone_type_id == 3 ? 'selected' : '' }}>
                                                                        Work</option>
                                                                    <option value="4"
                                                                        {{ $phone->phone_type_id == 4 ? 'selected' : '' }}>
                                                                        Other</option>
                                                                </select>
                                                                <input type="tel" name="phones[]"
                                                                    class="form-control @if($errors->has('phones') || $errors->has('phones.*')) is-invalid @endif" placeholder="Phone Number"
                                                                    value="{{ $phone->phone }}" maxlength="50" required>
                                                                <button type="button" class="btn btn-danger"
                                                                    onclick="removePhoneField(this)">
                                                                    <i class="feather-trash-2"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforeach
                                                @if ($lead->contactPhones->isEmpty())
                                                    <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-select" 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="tel" name="phones[]"
                                                                    class="form-control @if($errors->has('phones') || $errors->has('phones.*')) is-invalid @endif"
                                                                    placeholder="Phone Number" maxlength="50" required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endif
                                                <!-- Add new phone field button -->
                                                <div class="row align-items-center mb-2 phone-row">
                                                    <div class="col-md-12">
                                                        <div class="input-group">
                                                            <button type="button" class="btn btn-primary"
                                                                onclick="addPhoneField()">
                                                                <i class="feather-plus"></i> Add Phone
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                                @error('phones')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                                @error('phones.*')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                            </div>
                                        </div>


                                        <div id="emailContainer" class="col-md-6 mb-4">
                                            <div class="col-lg-4 mb-2">
                                                <label for="mailInput" class="fw-semibold">Email: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                @foreach ($lead->contactEmails as $email)
                                                    <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-select"
                                                                    name="email_types[]">
                                                                    <option value="1"
                                                                        {{ $email->email_type_id == 1 ? 'selected' : '' }}>
                                                                        Personal</option>
                                                                    <option value="2"
                                                                        {{ $email->email_type_id == 2 ? 'selected' : '' }}>
                                                                        Work</option>
                                                                    <option value="3"
                                                                        {{ $email->email_type_id == 3 ? 'selected' : '' }}>
                                                                        Other</option>
                                                                </select>
                                                                <input type="email" name="emails[]"
                                                                    class="form-control" placeholder="Email Address"
                                                                    value="{{ $email->email }}">
                                                                <button type="button" class="btn btn-danger"
                                                                    onclick="removeEmailField(this)">
                                                                    <i class="feather-trash-2"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforeach
                                                <!-- Add new email field button -->
                                                <div class="row align-items-center mb-2 email-row">
                                                    <div class="col-md-12">
                                                        <div class="input-group">
                                                            <button type="button" class="btn btn-primary"
                                                                onclick="addEmailField()">
                                                                <i class="feather-plus"></i> Add Email
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>



                                        <div class="col-12 lead-edit-section">
                                            <div class="lead-edit-section-title"><i class="feather-map-pin"></i>Location</div>
                                            <small>Update the Lead's address and regional information.</small>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <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">{{ old('address1', $lead->address_1) }}</textarea>
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-md-6 mb-4 align-items-center">
                                            <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">{{ old('address1', $lead->address_2) }}</textarea>
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-md-6 mb-4 align-items-center">
                                            <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" value="{{ old('city', $lead->city) }}"
                                                        placeholder="Enter City">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <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" value="{{ old('province', $lead->province) }}"
                                                        placeholder="Enter Province">
                                                </div>
                                            </div>
                                        </div>



                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Country: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-edit-icon-field">
                                                    <div class="input-group-text"><i class="feather-flag"></i></div>
                                                    <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->country_code ?? '') }}"
                                                                @selected((int) old('country_id', $lead->country_id) === (int) $country->id)>
                                                                {{ $country->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-12 lead-edit-section">
                                            <div class="lead-edit-section-title"><i class="feather-message-circle"></i>Communication Preferences</div>
                                            <small>Manage social channels, contact methods and languages.</small>
                                        </div>

                                        <div id="socialMediaContainer" class="col-md-6 mb-4 ">
                                            <div class="col-lg-4 mb-2">
                                                <label for="socialMediaInput" class="fw-semibold">Social
                                                    Media:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                @foreach ($lead->contactSocialMedia as $socialMedia)
                                                    <div class="row align-items-center mb-2 social-media-row">
                                                        <div class="col-md-12">
                                                            <div class="input-group">
                                                                <!-- Social Media Icon -->
                                                                <div class="input-group-text">
                                                                    @php
                                                                        $iconMapping = [
                                                                            'facebook' => 'feather-facebook',
                                                                            'twitter' => 'feather-twitter',
                                                                            'linkedin' => 'feather-linkedin',
                                                                            'instagram' => 'feather-instagram',
                                                                            'other' => 'feather-globe',
                                                                        ];

                                                                        $iconClass =
                                                                            $iconMapping[
                                                                                $socialMedia->social_media_type_id
                                                                            ] ?? 'feather-globe';
                                                                    @endphp
                                                                    <i class="{{ $iconClass }}"
                                                                        id="icon-{{ $socialMedia->social_media_type_id }}"></i>
                                                                </div>
                                                                <select class="form-select"
                                                                    name="social_media_types[]"
                                                                    onchange="changeSocialMediaIcon(this)">
                                                                    <option value="facebook"
                                                                        {{ (int) $socialMedia->social_media_type_id === 1 ? 'selected' : '' }}>
                                                                        Facebook</option>
                                                                    <option value="twitter"
                                                                        {{ (int) $socialMedia->social_media_type_id === 2 ? 'selected' : '' }}>
                                                                        Twitter</option>
                                                                    <option value="linkedin"
                                                                        {{ (int) $socialMedia->social_media_type_id === 3 ? 'selected' : '' }}>
                                                                        LinkedIn</option>
                                                                    <option value="instagram"
                                                                        {{ (int) $socialMedia->social_media_type_id === 4 ? 'selected' : '' }}>
                                                                        Instagram</option>
                                                                    <option value="other"
                                                                        {{ (int) $socialMedia->social_media_type_id === 5 ? 'selected' : '' }}>
                                                                        Other</option>
                                                                </select>
                                                                <!-- Social Media Handle or URL -->
                                                                <input type="text" name="social_media_values[]"
                                                                    class="form-control @if($errors->has('social_media_values.*')) is-invalid @endif" placeholder="Social Media URL"
                                                                    value="{{ $socialMedia->value }}">
                                                                <!-- Remove Button -->
                                                                <button type="button" class="btn btn-danger"
                                                                    onclick="removeSocialMediaField(this)">
                                                                    <i class="feather-trash-2"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforeach
                                                @error('social_media_types.*')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror
                                                @error('social_media_values.*')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror
                                                <!-- Add new social media field button -->
                                                <div class="row align-items-center mb-2 social-media-row">
                                                    <div class="col-md-12">
                                                        <div class="input-group">
                                                            <button type="button" class="btn btn-primary"
                                                                onclick="addSocialMediaField()">
                                                                <i class="feather-plus"></i> Add Social Media
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>



                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Contact Method:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group contact-method-field lead-one-line-multiselect">
                                                    <div class="input-group-text"><i class="feather-paperclip"></i></div>
                                                    <select class="form-control contact-method-one-line lead-one-line-select @error('contact_methods') is-invalid @enderror"
                                                        name="contact_methods[]" multiple data-lead-multiselect
                                                        data-placeholder="Select contact methods">
                                                        @foreach (['Phone', 'Email', 'Social Media', 'Postal Mail', 'Fax'] as $method)
                                                            <option value="{{ $method }}" @selected(in_array($method, $contactMethods, true))>
                                                                {{ $method }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                @error('contact_methods')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror
                                            </div>
                                        </div>




                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Languages:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                @php
                                                    $selectedLanguageIds = array_map('intval', old(
                                                        'languages',
                                                        $lead->contactLanguages->pluck('language_id')->all()
                                                    ));
                                                @endphp
                                                <div class="input-group language-field lead-one-line-multiselect">
                                                    <div class="input-group-text"><i class="feather-globe"></i></div>
                                                    <select class="form-control lead-one-line-select @error('languages') is-invalid @enderror"
                                                        name="languages[]" multiple data-lead-multiselect
                                                        data-placeholder="Select languages">
                                                        @foreach ($languages as $language)
                                                            <option value="{{ $language->id }}"
                                                                @selected(in_array((int) $language->id, $selectedLanguageIds, true))>
                                                                {{ $language->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                @error('languages')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror
                                            </div>
                                        </div>




                                        <div class="col-12 lead-edit-section">
                                            <div class="lead-edit-section-title"><i class="feather-trending-up"></i>Qualification</div>
                                            <small>Update pipeline status, product interest and record availability.</small>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Lead Status: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-edit-icon-field">
                                                    <div class="input-group-text"><i class="feather-trending-up"></i></div>
                                                    <select class="form-control" name="stage_id"
                                                        data-select2-selector="stage">
                                                    <option value="">Select Lead Status</option>
                                                    @foreach ($stages as $stage)
                                                        <option value="{{ $stage->id }}"
                                                            data-stage="bg-{{ strtolower($stage->name) }}"
                                                            {{ $lead->stage_id == $stage->id ? 'selected' : '' }}>
                                                            {{ $stage->name }}
                                                        </option>
                                                    @endforeach
                                                    </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">Interest Product:</label>
                                            </div>
                                            <div class="col-lg-12 lead-one-line-multiselect">
                                                <div class="input-group lead-edit-icon-field">
                                                    <div class="input-group-text"><i class="feather-package"></i></div>
                                                    <select class="form-control lead-one-line-select" name="interest_products[]"
                                                        multiple data-select2-selector="default">
                                                        @foreach ($products as $product)
                                                            <option value="{{ $product->id }}" @selected(in_array($product->id, array_map('intval', old('interest_products', $lead->interestProducts->pluck('id')->all())), true))>
                                                                {{ $product->product_name }}{{ $product->product_code ? ' · '.$product->product_code : '' }}
                                                            </option>
                                                        @endforeach
                                                    </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">Status: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-edit-icon-field">
                                                    <div class="input-group-text"><i class="feather-toggle-right"></i></div>
                                                    <select class="form-control" name="status"
                                                        data-select2-selector="status">
                                                    <option value="active" data-bg="bg-success"
                                                        {{ $lead->status == 'active' ? 'selected' : '' }}>
                                                        Active
                                                    </option>
                                                    <option value="inactive" data-bg="bg-warning"
                                                        {{ $lead->status == 'inactive' ? 'selected' : '' }}>
                                                        Inactive</option>
                                                    <option value="completed" data-bg="bg-primary"
                                                        {{ $lead->status == 'completed' ? 'selected' : '' }}>
                                                        Completed</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                    </div>
                                </div>
                                <div class="lead-edit-actions">
                                    <a href="{{ route('leads.view', ['id' => $lead->id]) }}" class="btn btn-light"><i class="feather-x me-1"></i>Cancel</a>
                                    <button type="submit" class="btn btn-primary"><i class="feather-save me-1"></i>Update Lead</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <!-- [ Main Content ] end -->
@endsection

@section('scripts')
    @php
        $requestedFocusField = in_array(request('focus'), [
            'first_name', 'emails', 'phones', 'job_title', 'company_id', 'languages',
            'lead_source', 'qualification', 'interest_products', 'address1', 'city',
            'country_id', 'zipcode', 'contact_methods',
        ], true) ? request('focus') : null;
    @endphp
    @if ($requestedFocusField)
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const fieldName = @json($requestedFocusField);
                const field = document.querySelector(`[name="${fieldName}"], [name="${fieldName}[]"]`);
                if (!field) return;

                const fieldSection = field.closest('.col-md-6, .col-md-12') || field;
                fieldSection.scrollIntoView({ behavior: 'smooth', block: 'center' });
                window.setTimeout(function () {
                    if (field.matches('select') && window.jQuery && jQuery.fn.select2 && jQuery(field).hasClass('select2-hidden-accessible')) {
                        jQuery(field).select2('open');
                    } else {
                        field.focus({ preventScroll: true });
                    }
                }, 350);
            });
        </script>
    @endif
    <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-select" 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="tel" name="phones[]" class="form-control" placeholder="Phone Number" maxlength="50" required>
                    <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-select" 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-select" name="social_media_types[]" onchange="changeSocialMediaIcon(this)">
                        <option value="">Select Platform</option>
                        <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;
            }
        }
    </script>

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

    <script>
        $(document).ready(function() {
            $('#lead-source-dropdown').select2({
                placeholder: "Select Lead Source",
                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>
    <!--! END: Theme Customizer !-->
@endsection
