@extends('layouts.app')

@section('title', 'Tickets View')

@section('content')
    @include('shared.crm-professional-ui')
    <div class="page-header crm-professional-header">
        <div class="page-header-left d-flex align-items-center">
            <div class="page-header-title">
                <h5 class="mb-1">Ticket Profile</h5>
                <small class="text-muted d-none d-lg-block">Ticket #{{ str_pad((string) $ticket->id, 4, '0', STR_PAD_LEFT) }}</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">
                    @can('create_contacts')
                        <a href="{{ route('contacts-create', ['ticketId' => $ticket->id]) }}" class="btn btn-light-brand">
                            <i class="feather-arrow-right-circle me-2"></i><span>Move to Contact</span>
                        </a>
                    @endcan
                    @can('create_leads')
                        <a href="{{ route('leads-create', ['ticketId' => $ticket->id]) }}" class="btn btn-light-brand">
                            <i class="feather-arrow-right-circle me-2"></i><span>Move to Lead</span>
                        </a>
                    @endcan
                    @can('create_deals')
                        <a href="{{ route('deals-create', ['ticketId' => $ticket->id]) }}" class="btn btn-light-brand">
                            <i class="feather-arrow-right-circle me-2"></i><span>Move to Deal</span>
                        </a>
                    @endcan
                    <a href="{{ route('ticket-create') }}" class="btn btn-primary">
                        <i class="feather-plus me-2"></i>
                        <span>Create Ticket</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 crm-professional-profile">

        <div class="row">
            {{-- <div class="col-xxl-4 col-xl-6">
                <div class="card stretch stretch-full">
                    <div class="card-body">
                        <div class="mb-4 text-center">

                            <div class="mb-4">
                                <a href="javascript:void(0);" class="fs-20 fw-bold d-block">
                                    {{ $ticket->topic }}</a>
                                <a href="javascript:void(0);" class="fs-12 fw-normal text-muted d-block">
                                    {{ $ticket->email }}
                                </a>
                            </div>

                        </div>
                        <ul class="list-unstyled mb-4">

                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-phone"></i>Phone</span>

                                <a href="javascript:void(0);" class="float-end">
                                    {{ $ticket->phone }}
                                </a>

                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-mail"></i>Email</span>
                                <a href="javascript:void(0);" class="float-end">
                                    {{ $ticket->email }}
                                </a>

                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-user"></i>
                                    Contact Name:</span>
                                <span class="fw-semibold">{{ $ticket->contact_name }}</span>
                            </li>

                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-calendar"></i> Date
                                    Date:</span>
                                <span class="fw-semibold">
                                    {{ $ticket->date_time ? \Carbon\Carbon::parse($ticket->date_time)->format('Y-m-d\TH:i') : '' }}</span>
                            </li>

                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-book"></i>
                                    Languages:</span>
                                <span class="fw-semibold">
                                    @foreach ($ticket->ticketLanguages as $ticketLanguage)
                                        @php
                                            $language = \App\Models\Language::find($ticketLanguage->language_id);
                                        @endphp
                                        {{ $language ? $language->name : 'No Languages' }},
                                    @endforeach
                                </span>
                            </li>

                        </ul>
                        <div class="d-flex gap-2 text-center pt-4">
                            <a href="javascript:void(0);" class="w-50 btn btn-light-brand">
                                <i class="feather-trash-2 me-2"></i>
                                <span>Delete</span>
                            </a>
                            <a href="{{ route('ticket.edit') }}?id={{ $ticket->id }}" class="w-50 btn btn-primary">
                                <i class="feather-edit me-2"></i>
                                <span>Edit Profile</span>
                            </a>
                        </div>
                        <div class="card-body">


                            <div class="d-flex align-items-center mb-3">
                                <div class="avatar-text bg-gray-100">
                                    <i class="feather feather-globe"></i>
                                </div>
                                <span class="mx-2 text-gray-300">/</span>
                                <a href="" target="_blank" class="text-truncate-1-line">
                                    {{ $ticket->social_media }}
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            <div class="col-xxl-8 col-xl-6">
                <div class="card border-top-0">
                    <div class="card-header p-0">

                    </div>

                </div>
            </div> --}}


            <div class="content-sidebar content-sidebar-md" data-scrollbar-target="#psScrollbarInit">

                <div class="content-sidebar-body mt-2">
                    <ul class="nav flex-column nxl-content-sidebar-item customers-nav-tabs sidebar-style" id="myTab"
                        role="tablist">
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link active" id="overallTabLink" data-bs-toggle="tab"
                                data-bs-target="#overallTab" role="tab" aria-controls="overallTab"
                                aria-selected="true">
                                <i class="feather-pie-chart"></i>
                                <span>Overview</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="meetingTabLink" data-bs-toggle="tab"
                                data-bs-target="#meetingTab" role="tab" aria-controls="meetingTab"
                                aria-selected="false">
                                <i class="feather-calendar"></i>
                                <span>Invite Meeting</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="activityTabLink" data-bs-toggle="tab"
                                data-bs-target="#activityTab" role="tab" aria-controls="activityTab"
                                aria-selected="false">
                                <i class="feather-activity"></i>
                                <span>Activities</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="productTabLink" data-bs-toggle="tab"
                                data-bs-target="#productTab" role="tab" aria-controls="productTab"
                                aria-selected="false">
                                <i class="feather-box"></i>
                                <span>Product</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="accountDetailsTabLink" data-bs-toggle="tab"
                                data-bs-target="#accountDetailsTab" role="tab" aria-controls="accountDetailsTab"
                                aria-selected="false">
                                <i class="feather-user"></i>
                                <span>Account Details</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="campaignTabLink" data-bs-toggle="tab"
                                data-bs-target="#campaignTab" role="tab" aria-controls="campaignTab"
                                aria-selected="false">
                                <i class="feather-mic"></i>
                                <span>Campaign</span>
                            </a>
                        </li>
                    </ul>


                </div>
            </div>

            <div class="col min-w-0">

                <div class="card border-top-0">
                    <div class="card stretch stretch-full">
                        <div class="card-body task-header d-md-flex align-items-center justify-content-between">
                            <div class="me-4">
                                <h4 class="mb-4 fw-bold d-flex align-items-center">
                                    <span class="text-truncate-1-line">
                                        {{ $ticket->topic }}
                                        <span class="badge bg-soft-primary text-primary mx-3">
                                            @php
                                                // Fetch the first non-completed stage status for the ticket
                                                $ticketStageStatus = \App\Models\TicketStageStatus::where(
                                                    'ticket_id',
                                                    $ticket->id,
                                                )
                                                    ->where('stage_status', '!=', 3) // Stage status not 'Completed'
                                                    ->first();

                                                if ($ticketStageStatus) {
                                                    // Fetch the stage name for the found stage ID
                                                    $stageName = \App\Models\TicketStage::where(
                                                        'id',
                                                        $ticketStageStatus->stage_id,
                                                    )->first()->name;
                                                } else {
                                                    // Default to the current stage of the ticket
                                                    $stageName = \App\Models\TicketStage::where(
                                                        'id',
                                                        $ticket->stage_id,
                                                    )->first()->name;
                                                }
                                            @endphp

                                            {{ $stageName }}
                                        </span>
                                    </span>

                                </h4>

                                <div>
                                    <div class="row">
                                        <!-- Left Column -->
                                        <div class="col-md-6">


                                            <!-- Company -->
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="feather-users text-info me-2"></i>
                                                <span class="text-muted">
                                                    {{ \App\Models\Contact::find($ticket->primary_contact_id)->first_name ?? '-' }}
                                                </span>
                                            </div>
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="feather-mail text-primary me-2"></i>
                                                <span class="text-muted">
                                                    {{ $ticket->email }}
                                                </span>
                                            </div>


                                        </div>

                                        <!-- Right Column -->
                                        <div class="col-md-6">

                                            <!-- Phone -->
                                            <div class="d-flex align-items-center mb-3">
                                                <i class="feather-phone text-success me-2"></i>
                                                <span class="text-muted">
                                                    {{ $ticket->phone }}
                                                </span>
                                            </div>

                                            <div class="d-flex align-items-center mb-3">
                                                <i class="feather-users text-warning me-2"></i>
                                                <span class="text-muted">
                                                    {{ $ticket->contact_name }}
                                                </span>
                                            </div>
                                        </div>

                                    </div>

                                </div>

                                <div class="d-flex align-items-center">
                                    <div class="dropdown">
                                        <a class="btn btn-icon btn-light-brand dropdown-toggle" data-bs-toggle="dropdown"
                                            data-bs-offset="0, 10">
                                            Activities
                                        </a>
                                        <div class="dropdown-menu wd-300">


                                            <!-- Add Note Icon -->
                                            <a href="{{ route('schedule-activity-create') }}" class="dropdown-item">
                                                <i class="feather feather-edit-3 me-2"></i>
                                                <span>Add Note</span>
                                            </a>


                                            <a href="{{ route('schedule-activity-create') }}" class="dropdown-item">
                                                <i class="feather feather-mail me-2"></i>
                                                <span>Send Mail</span>
                                            </a>
                                            <!-- <a href="#" class="dropdown-item">
                                                <i class="feather feather-phone-call me-2"></i>
                                                <span>Make Call</span>
                                            </a>
                                            <a href="#" class="dropdown-item">
                                                <i class="feather feather-message-square me-2"></i>
                                                <span>Add SMS</span>
                                            </a> -->

                                        </div>
                                    </div>

                                    {{-- <span class="vr mx-3 text-muted"></span> --}}

                                </div>
                            </div>
                            <div class="mt-4 mt-md-0">
                                <div class="d-flex gap-2">
                                    <select class="form-control update-stage" data-id="{{ $ticket->id }}"
                                        data-select2-selector="status">
                                        @php
                                            // Fetch the first TicketStageStatus where stage_status is not 3 (Completed)
                                            $ticketStageStatus = \App\Models\TicketStageStatus::where(
                                                'ticket_id',
                                                $ticket->id,
                                            )
                                                ->where('stage_status', '!=', 3)
                                                ->first();

                                            // Determine the current stage ID
                                            $currentStageId = $ticketStageStatus
                                                ? $ticketStageStatus->stage_id
                                                : $ticket->stage_id;
                                        @endphp

                                        @foreach ($stages as $stage)
                                            <option value="{{ $stage->id }}" data-bg="bg-success"
                                                @selected($currentStageId == $stage->id)>
                                                {{ $stage->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="tab-content">
                        <!-- Activity Tab Content -->
                        <div class="tab-pane fade show active p-4" id="overallTab" role="tabpanel"
                            aria-labelledby="overallTabLink">

                            <div class="pb-5">
                                <div class="arrow-steps clearfix">
                                    @php
                                        $stages = [
                                            'Qualified' => [
                                                'Marketing Qualified' => ['None', 'Mark', 'Completed'],
                                                'Sales Qualified Lead' => ['None', 'Mark', 'Completed'],
                                                'Campaign Assesment' => ['None', 'Mark', 'Completed'],
                                            ],
                                            'In Progress' => [
                                                'Introductory Meeting' => ['None', 'Mark', 'Completed'],
                                                'Needs Analysis' => ['None', 'Mark', 'Completed'],
                                                'Attempted to Ticket' => ['None', 'Mark', 'Completed'],
                                                'Interested' => ['None', 'Mark', 'Completed'],
                                            ],
                                            'Close' => [
                                                'Closed WON' => [],
                                                'Closed LOST' => [],
                                            ],
                                        ];

                                        $stageMap = [
                                            'Marketing Qualified' => 1,
                                            'Sales Qualified Lead' => 2,
                                            'Campaign Assesment' => 3,
                                            'Introductory Meeting' => 4,
                                            'Needs Analysis' => 5,
                                            'Attempted to Ticket' => 6,
                                            'Interested' => 7,
                                            'Closed WON' => 8,
                                            'Closed LOST' => 9,
                                        ];

                                        function areAllSubStagesCompleted($ticketId, $subStages, $stageMap)
                                        {
                                            foreach ($subStages as $subStageName => $actions) {
                                                $currentStatus = \DB::table('ticket_stage_statuses')
                                                    ->where('ticket_id', $ticketId)
                                                    ->where('stage_id', $stageMap[$subStageName])
                                                    ->value('stage_status');
                                                if ($currentStatus !== 3) {
                                                    return false;
                                                }
                                            }
                                            return true;
                                        }

                                        $currentStage = null;
                                        foreach ($stages as $stageName => $subStages) {
                                            if ($currentStage === null) {
                                                $allCompleted = areAllSubStagesCompleted(
                                                    $ticket->id,
                                                    $subStages,
                                                    $stageMap,
                                                );
                                                if (!$allCompleted) {
                                                    $currentStage = $stageName;
                                                    break;
                                                }
                                            }
                                        }

                                        if ($currentStage === null) {
                                            $currentStage = array_key_last($stages);
                                        }
                                    @endphp

                                    @foreach ($stages as $stageName => $subStages)
                                        <div
                                            class="step {{ $currentStage === $stageName || areAllSubStagesCompleted($ticket->id, $subStages, $stageMap) ? 'current' : '' }}">
                                            <span id="{{ Str::slug($stageName) }}" class="dropdown-toggle"
                                                data-bs-toggle="dropdown" aria-expanded="false"
                                                @if (
                                                    ($stageName === 'In Progress' && !areAllSubStagesCompleted($ticket->id, $stages['Qualified'], $stageMap)) ||
                                                        ($stageName === 'Close' && !areAllSubStagesCompleted($ticket->id, $stages['In Progress'], $stageMap))) style="pointer-events: none; opacity: 0.6;" @endif>
                                                {{ $stageName }}
                                            </span>

                                            @if ($stageName === 'Close')
                                                <ul class="dropdown-menu p-2"
                                                    aria-labelledby="{{ Str::slug($stageName) }}">
                                                    <li>
                                                        <button type="button" class="btn text-start w-100"
                                                            data-bs-toggle="modal" data-bs-target="#closedWonModal">
                                                            Closed WON
                                                        </button>
                                                    </li>
                                                    <li>
                                                        <button type="button" class="btn text-start w-100"
                                                            data-bs-toggle="modal" data-bs-target="#closedLostModal">
                                                            Closed LOST
                                                        </button>
                                                    </li>
                                                </ul>
                                            @else
                                                <ul class="dropdown-menu p-2"
                                                    aria-labelledby="{{ Str::slug($stageName) }}">
                                                    @foreach ($subStages as $subStageName => $actions)
                                                        @php
                                                            $currentStatus =
                                                                \DB::table('ticket_stage_statuses')
                                                                    ->where('ticket_id', $ticket->id)
                                                                    ->where('stage_id', $stageMap[$subStageName])
                                                                    ->value('stage_status') ?? 1;
                                                        @endphp
                                                        <li class="dropdown-submenu">
                                                            <a class="dropdown-item d-flex align-items-center justify-content-between"
                                                                href="#">
                                                                <span style="flex-grow: 1;">{{ $subStageName }}</span>
                                                                <div style="padding-left: 10px;">
                                                                    <select class="form-select stage-status-select"
                                                                        style="width: 110px; font-size: 13px;"
                                                                        data-stage-id="{{ $stageMap[$subStageName] }}"
                                                                        data-ticket-id="{{ $ticket->id }}">
                                                                        <option value="None"
                                                                            {{ $currentStatus == 1 ? 'selected' : '' }}>
                                                                            None</option>
                                                                        <option value="Mark"
                                                                            {{ $currentStatus == 2 ? 'selected' : '' }}>
                                                                            Mark</option>
                                                                        <option value="Completed"
                                                                            {{ $currentStatus == 3 ? 'selected' : '' }}>
                                                                            Completed</option>
                                                                    </select>
                                                                </div>
                                                            </a>
                                                        </li>
                                                    @endforeach
                                                </ul>
                                            @endif
                                        </div>
                                    @endforeach
                                </div>
                            </div>


                            <div class="pt-0 px-5 pb-5">
                                <div class="row">


                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-user"></i>Contact Name:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ \App\Models\Contact::find($ticket->primary_contact_id)->first_name ?? '-' }}
                                            </a>
                                        </div>
                                    </div>



                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-phone"></i>Mobile Number:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $ticket->phone }}
                                            </a>
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-mail"></i>Email:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $ticket->email }}
                                            </a>
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-globe"></i>SIC Code:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $ticket->social_media }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-flag"></i>Priority:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $ticket->priority->name ?? 'Not Assigned' }}
                                            </a>
                                        </div>
                                    </div>





                                </div>
                            </div>



                        </div>
                        <!-- Activity Tab Content -->
                        <div class="tab-pane fade p-4" id="activityTab" role="tabpanel"
                            aria-labelledby="activityTabLink">

                            <x-crm-related-workflows module="tickets" :record="$ticket" />

                            <div class="profile-details mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-end">
                                    <a href="{{ route('schedule-activity-create') }}?ticketId={{ $ticket->id }}"
                                        class="btn btn-sm btn-light-brand">Create
                                        Activity</a>
                                    <a href="{{ route('related-activity.index', ['tickets', $ticket->id]) }}"
                                        class="btn btn-sm btn-outline-primary ms-2">Messages, Notes, Follow-ups &amp; To-dos</a>
                                </div>

                                @php
                                    $futureActivities = $activities->filter(function ($activity) {
                                        $activityDate =
                                            $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                        return $activityDate &&
                                            \Carbon\Carbon::parse($activityDate)->isFuture() &&
                                            $activity->activity_type_id != 2;
                                    });
                                @endphp

                                @if ($futureActivities->isNotEmpty())
                                    <div class="profile-details mb-5">
                                        <div class="mb-4 d-flex align-items-center justify-content-between">
                                            <h5 class="fw-bold mb-0">Scheduled Activities:</h5>

                                            <div class="card-body custom-card-action">
                                                <ul class="list-unstyled mb-0 activity-feed-1">
                                                    @foreach ($activities as $activity)
                                                        @php
                                                            $activityDate =
                                                                $activity->end_date ??
                                                                ($activity->due_date ?? $activity->close_by);
                                                        @endphp

                                                        @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isFuture() && $activity->activity_type_id != 2)
                                                            <li class="feed-item feed-item-primary">
                                                                <div class="d-flex gap-4 justify-content-between">
                                                                    <div>
                                                                        <div class="mb-2 text-truncate-1-line">
                                                                            <a href="javascript:void(0)"
                                                                                class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                        </div>
                                                                        <p
                                                                            class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                            {{ $activity->description }}
                                                                        </p>

                                                                        <div>
                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-success border border-dashed border-gray-500">
                                                                                Start-
                                                                                {{ \Carbon\Carbon::parse($activity->start_date ?? ($activity->due_date ?? $activity->received_on))->format('Y-m-d') }}
                                                                            </a>

                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-danger border border-dashed border-gray-500">
                                                                                End-
                                                                                {{ \Carbon\Carbon::parse($activity->end_date ?? ($activity->due_date ?? $activity->close_by))->format('Y-m-d') }}
                                                                            </a>
                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-warning border border-dashed border-gray-500">Duration-
                                                                                {{ $activity->duration }}</a>
                                                                        </div>
                                                                    </div>
                                                                    <div
                                                                        class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                        {{ $activity->created_at->diffForHumans() }}
                                                                    </div>
                                                                </div>
                                                            </li>
                                                        @endif
                                                    @endforeach
                                                </ul>


                                            </div>
                                        </div>
                                    </div>
                                    <hr class="my-0">

                                @endif
                                @php
                                    $futureActivities = $activities->filter(function ($activity) {
                                        $activityDate =
                                            $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                        return $activityDate &&
                                            \Carbon\Carbon::parse($activityDate)->isPast() &&
                                            $activity->activity_type_id != 2;
                                    });
                                @endphp

                                @if ($futureActivities->isNotEmpty())

                                    <div class="profile-details mb-5">
                                        <div class="mb-4 d-flex align-items-center justify-content-between">
                                            <h5 class="fw-bold mb-0">Expired Activities:</h5>

                                            <div class="card-body custom-card-action">
                                                <ul class="list-unstyled mb-0 activity-feed-1">
                                                    @foreach ($activities as $activity)
                                                        @php
                                                            $activityDate =
                                                                $activity->end_date ??
                                                                ($activity->due_date ?? $activity->close_by);
                                                        @endphp

                                                        @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isPast())
                                                            <li class="feed-item feed-item-primary">
                                                                <div class="d-flex gap-4 justify-content-between">
                                                                    <div>
                                                                        <div class="mb-2 text-truncate-1-line">
                                                                            <a href="javascript:void(0)"
                                                                                class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                        </div>
                                                                        <p
                                                                            class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                            {{ $activity->description }}
                                                                        </p>
                                                                        <div>
                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-success border border-dashed border-gray-500">
                                                                                Start-
                                                                                {{ $activity->start_date ?? ($activity->due_date ?? $activity->received_on) }}
                                                                            </a>
                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-danger border border-dashed border-gray-500">
                                                                                End-
                                                                                {{ $activity->end_date ?? ($activity->due_date ?? $activity->close_by) }}
                                                                            </a>
                                                                        </div>
                                                                    </div>
                                                                    <div
                                                                        class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                        {{ $activity->created_at->diffForHumans() }}
                                                                    </div>
                                                                </div>
                                                            </li>
                                                        @endif
                                                    @endforeach
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                @endif
                            </div>

                        </div>

                        <!-- Note Tab Content -->
                        <div class="tab-pane fade p-4" id="noteTab" role="tabpanel" aria-labelledby="noteTabLink">


                            <form action="{{ route('notes.store') }}" method="post">
                                @csrf

                                <input type="hidden" name="contact_id" value="{{ request('id') }}">
                                <div class="mb-3">
                                    <label for="noteTitle" class="form-label">Note Title</label>
                                    <input type="text" class="form-control" id="noteTitle" name="noteTitle"
                                        placeholder="Enter note title" required>
                                </div>
                                <div class="mb-3">
                                    <label for="noteDescription" class="form-label">Note Description</label>
                                    <textarea class="form-control" id="noteDescription" name="noteDescription" rows="4"
                                        placeholder="Enter note description" required></textarea>
                                </div>
                                <div class="d-flex justify-content-end">
                                    <button type="submit" class="btn btn-primary">Add Note</button>
                                </div>
                            </form>


                            <div class="profile-details mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-between">
                                    <h5 class="fw-bold mb-0">Notes:</h5>
                                </div>

                                <div class="row">
                                    @foreach ($notes as $note)
                                        <div
                                            class="col-xxl-4 col-xl-6 col-lg-4 col-sm-6 single-note-item all-category note-important note-archive">
                                            <div class="card card-body mb-4 stretch stretch-full">
                                                <span class="side-stick"></span>
                                                <h5 class="note-title text-truncate w-75 mb-1"
                                                    data-noteheading="{{ $note->title }}">
                                                    {{ $note->title }}
                                                    <i class="point bi bi-circle-fill ms-1 fs-7"></i>
                                                </h5>
                                                <p class="fs-11 text-muted note-date">
                                                    {{ $note->created_at->format('d M Y') }}
                                                </p>
                                                <div class="note-content flex-grow-1">
                                                    <p class="text-muted note-inner-content text-truncate-3-line"
                                                        data-notecontent="{{ $note->description }}">
                                                        {{ $note->description }}
                                                    </p>
                                                </div>
                                                <div class="d-flex align-items-center gap-1">
                                                    <span class="avatar-text avatar-sm">
                                                        <i class="feather-star favourite-note"></i>
                                                    </span>
                                                    <span class="avatar-text avatar-sm">
                                                        <i class="feather-trash-2 remove-note"></i>
                                                    </span>
                                                    <div class="ms-auto">
                                                        <div class="dropdown btn-group category-selector">
                                                            <a class="nav-link dropdown-toggle category-dropdown label-group p-0"
                                                                data-bs-toggle="dropdown" href="#" role="button"
                                                                aria-haspopup="true" aria-expanded="true">
                                                                <div class="category">
                                                                    <div class="category-business"></div>
                                                                    <div class="category-social"></div>
                                                                    <div class="category-important"></div>
                                                                </div>
                                                            </a>
                                                            <div class="dropdown-menu dropdown-menu-right category-menu">
                                                                <a class="note-tasks badge-group-item badge-tasks dropdown-item position-relative category-tasks"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-danger rounded-circle me-3"></span>Tasks
                                                                </a>
                                                                <a class="note-works badge-group-item badge-works dropdown-item position-relative category-works"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-primary rounded-circle me-3"></span>Works
                                                                </a>
                                                                <a class="note-social badge-group-item badge-social dropdown-item position-relative category-social"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-info rounded-circle me-3"></span>Social
                                                                </a>
                                                                <a class="note-archive badge-group-item badge-archive dropdown-item position-relative category-archive"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-dark rounded-circle me-3"></span>Archive
                                                                </a>
                                                                <a class="note-priority badge-group-item badge-priority dropdown-item position-relative category-priority"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-danger rounded-circle me-3"></span>Priority
                                                                </a>
                                                                <a class="note-personal badge-group-item badge-personal dropdown-item position-relative category-personal"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-primary rounded-circle me-3"></span>Personal
                                                                </a>
                                                                <a class="note-business badge-group-item badge-business dropdown-item position-relative category-business"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-warning rounded-circle me-3"></span>Business
                                                                </a>
                                                                <a class="note-important badge-group-item badge-important dropdown-item position-relative category-important"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-success rounded-circle me-3"></span>Important
                                                                </a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>




                            </div>
                        </div>

                        <!-- Meeting Tab Content -->
                        <div class="tab-pane fade p-4" id="meetingTab" role="tabpanel" aria-labelledby="meetingTabLink">
                            <!-- Content for Meeting Tab -->
                            <div class="about-section mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-end">
                                    <a href="{{ route('schedule-activity-create') }}?id={{ $ticket->id }}"
                                        class="btn btn-sm btn-light-brand">Create Meeting</a>
                                </div>
                            </div>
                            @php
                                $futureMeetings = $activities->filter(function ($activity) {
                                    $activityDate = $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                    return $activityDate &&
                                        \Carbon\Carbon::parse($activityDate)->isFuture() &&
                                        $activity->activity_type_id == 2;
                                });
                            @endphp

                            @if ($futureMeetings->isNotEmpty())
                                <div class="profile-details mb-5">
                                    <div class="mb-4 d-flex align-items-center justify-content-between">
                                        <h5 class="fw-bold mb-0">Scheduled Meetings:</h5>

                                        <div class="card-body custom-card-action">
                                            <ul class="list-unstyled mb-0 activity-feed-1">
                                                @foreach ($activities as $activity)
                                                    @php
                                                        $activityDate =
                                                            $activity->end_date ??
                                                            ($activity->due_date ?? $activity->close_by);
                                                    @endphp

                                                    @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isFuture() && $activity->activity_type_id == 2)
                                                        <li class="feed-item feed-item-primary">
                                                            <div class="d-flex gap-4 justify-content-between">
                                                                <div>
                                                                    <div class="mb-2 text-truncate-1-line">
                                                                        <a href="javascript:void(0)"
                                                                            class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                    </div>
                                                                    <p class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                        {{ $activity->description }}
                                                                    </p>

                                                                    <div>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-success border border-dashed border-gray-500">
                                                                            Start-
                                                                            {{ \Carbon\Carbon::parse($activity->start_date ?? ($activity->due_date ?? $activity->received_on))->format('Y-m-d') }}
                                                                        </a>

                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-danger border border-dashed border-gray-500">
                                                                            End-
                                                                            {{ \Carbon\Carbon::parse($activity->end_date ?? ($activity->due_date ?? $activity->close_by))->format('Y-m-d') }}
                                                                        </a>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-warning border border-dashed border-gray-500">Duration-
                                                                            {{ $activity->duration }}</a>
                                                                    </div>
                                                                </div>
                                                                <div
                                                                    class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                    {{ $activity->created_at->diffForHumans() }}
                                                                </div>
                                                            </div>
                                                        </li>
                                                    @endif
                                                @endforeach
                                            </ul>


                                        </div>
                                    </div>

                                </div>
                            @endif

                            @php
                                $futureMeetings = $activities->filter(function ($activity) {
                                    $activityDate = $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                    return $activityDate &&
                                        \Carbon\Carbon::parse($activityDate)->isPast() &&
                                        $activity->activity_type_id == 2;
                                });
                            @endphp

                            @if ($futureMeetings->isNotEmpty())
                                <div class="profile-details mb-5">
                                    <div class="mb-4 d-flex align-items-center justify-content-between">
                                        <h5 class="fw-bold mb-0">Expired Meetings:</h5>

                                        <div class="card-body custom-card-action">
                                            <ul class="list-unstyled mb-0 activity-feed-1">
                                                @foreach ($activities as $activity)
                                                    @php
                                                        $activityDate =
                                                            $activity->end_date ??
                                                            ($activity->due_date ?? $activity->close_by);
                                                    @endphp

                                                    @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isPast() && $activity->activity_type_id == 2)
                                                        <li class="feed-item feed-item-primary">
                                                            <div class="d-flex gap-4 justify-content-between">
                                                                <div>
                                                                    <div class="mb-2 text-truncate-1-line">
                                                                        <a href="javascript:void(0)"
                                                                            class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                    </div>
                                                                    <p class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                        {{ $activity->description }}
                                                                    </p>

                                                                    <div>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-success border border-dashed border-gray-500">
                                                                            Start-
                                                                            {{ \Carbon\Carbon::parse($activity->start_date ?? ($activity->due_date ?? $activity->received_on))->format('Y-m-d') }}
                                                                        </a>

                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-danger border border-dashed border-gray-500">
                                                                            End-
                                                                            {{ \Carbon\Carbon::parse($activity->end_date ?? ($activity->due_date ?? $activity->close_by))->format('Y-m-d') }}
                                                                        </a>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-warning border border-dashed border-gray-500">Duration-
                                                                            {{ $activity->duration }}</a>
                                                                    </div>
                                                                </div>
                                                                <div
                                                                    class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                    {{ $activity->created_at->diffForHumans() }}
                                                                </div>
                                                            </div>
                                                        </li>
                                                    @endif
                                                @endforeach
                                            </ul>


                                        </div>
                                    </div>

                                </div>
                            @endif

                        </div>

                        <!-- Email Tab Content -->
                        <div class="tab-pane fade p-4" id="emailTab" role="tabpanel" aria-labelledby="emailTabLink">
                            <!-- Content for Email Tab -->
                            <div class="about-section mb-5">


                                <div class="modal-content">
                                    <!--! BEGIN: [modal-header] !-->
                                    <div class="modal-header">
                                        <h2 class="d-flex flex-column mb-0">
                                            <span class="fs-18 fw-bold mb-1">Compose Mail</span>

                                        </h2>

                                    </div>
                                    <!--! BEGIN: [modal-body] !-->
                                    <div class="modal-body p-0">
                                        <div class="position-relative border-bottom">
                                            <div class="px-2 d-flex align-items-center">
                                                <div class="p-0 w-100">
                                                    <input class="form-control border-0 text-dark" name="tomailmodal"
                                                        placeholder="TO">
                                                </div>
                                            </div>
                                            <a href="javascript:void(0)"
                                                class="position-absolute top-50 end-0 translate-middle badge bg-gray-100 border border-gray-3 fs-10 fw-semibold text-uppercase text-dark rounded-pill c-pointer z-index-100"
                                                id="ccbccToggleModal"><span data-bs-toggle="tooltip"
                                                    data-bs-trigger="hover" title="CC / BCC"
                                                    style="font-size: 9px !important">CC / BCC</span></a>
                                        </div>
                                        <div class="border-bottom mail-cc-bcc-fields" id="ccbccToggleModalFileds"
                                            style="display: none">
                                            <div class="px-2 w-100 d-flex align-items-center border-bottom">
                                                <input class="form-control border-0 text-dark" name="ccmailmodal"
                                                    placeholder="CC">
                                            </div>
                                            <div class="px-2 w-100 d-flex align-items-center">
                                                <input class="form-control border-0 text-dark" name="bccmailmodal"
                                                    placeholder="BCC">
                                            </div>
                                        </div>
                                        <div class="px-3 w-100 d-flex align-items-center">
                                            <input class="form-control border-0 my-1 w-100 shadow-none" type="email"
                                                placeholder="Subject">
                                        </div>
                                        <div class="px-3">
                                            <textarea class="form-control border-0 text-dark" rows="8" placeholder="Write here..."></textarea>
                                        </div>
                                    </div>
                                    <!--! BEGIN: [modal-footer] !-->
                                    <div class="modal-footer d-flex align-items-center justify-content-between">
                                        <!--! BEGIN: [mail-editor-action-left] !-->
                                        <div class="d-flex align-items-center">
                                            <div class="dropdown me-2">
                                                <a href="javascript:void(0)" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 0">
                                                    <span class="btn btn-primary dropdown-toggle" data-bs-toggle="tooltip"
                                                        data-bs-trigger="hover" title="Send Message"> Send </span>
                                                </a>
                                                <div class="dropdown-menu">
                                                    <a href="javascript:void(0)" class="dropdown-item"
                                                        data-action-target="#mailActionMessage">
                                                        <i class="feather-send me-3"></i>
                                                        <span>Instant Send</span>
                                                    </a>
                                                    <a href="javascript:void(0);"
                                                        class="dropdown-item successAlertMessage">
                                                        <i class="feather-clock me-3"></i>
                                                        <span>Schedule Send</span>
                                                    </a>
                                                    <div class="dropdown-divider"></div>
                                                    <a href="javascript:void(0)"
                                                        class="dropdown-item successAlertMessage">
                                                        <i class="feather-x me-3"></i>
                                                        <span>Discard Now</span>
                                                    </a>
                                                    <a href="javascript:void(0)"
                                                        class="dropdown-item successAlertMessage">
                                                        <i class="feather-edit-3 me-3"></i>
                                                        <span>Save as Draft</span>
                                                    </a>
                                                </div>
                                            </div>
                                            <div class="dropdown me-2 d-none d-sm-block">
                                                <a href="javascript:void(0)" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 0">
                                                    <span class="btn btn-icon" data-bs-toggle="tooltip"
                                                        data-bs-trigger="hover" title="Pick Template">
                                                        <i class="feather-hash"></i>
                                                    </span>
                                                </a>
                                                <div class="dropdown-menu wd-300">
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Welcome you message</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Your issues solved</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Thank you message</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Make a offer message</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Add the Unsubscribe option</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Thank your customer for joining</span>
                                                    </a>
                                                    <div class="dropdown-divider"></div>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-save me-3"></i>
                                                        <span>Save as Template</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-sun me-3"></i>
                                                        <span>Manage Template</span>
                                                    </a>
                                                </div>
                                            </div>
                                            <div class="dropdown">
                                                <a href="javascript:void(0)" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 0">
                                                    <span class="btn btn-icon" data-bs-toggle="tooltip"
                                                        data-bs-trigger="hover" title="Upload Attachments">
                                                        <i class="feather-upload"></i>
                                                    </span>
                                                </a>
                                                <div class="dropdown-menu">
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-image me-3"></i>
                                                        <span>Upload Images</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-video me-3"></i>
                                                        <span>Upload Videos</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-mic me-3"></i>
                                                        <span>Upload Musics</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Upload Documents</span>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                        <!--! BEGIN: [mail-editor-action-right] !-->
                                        <div class="d-flex align-items-center">
                                            <div class="dropdown me-2">
                                                <a href="javascript:void(0)" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 0">
                                                    <span class="btn btn-icon" data-bs-toggle="tooltip"
                                                        data-bs-trigger="hover" title="Editing Actions">
                                                        <i class="feather-more-horizontal"></i>
                                                    </span>
                                                </a>
                                                <ul class="dropdown-menu">
                                                    <li>
                                                        <a href="javascript:void(0)" class="dropdown-item">
                                                            <i class="feather-type me-3"></i>
                                                            <span>Plain Text Mode</span>
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a href="javascript:void(0)" class="dropdown-item">
                                                            <i class="feather-check me-3"></i>
                                                            <span>Check Spelling</span>
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a href="javascript:void(0)" class="dropdown-item">
                                                            <i class="feather-compass me-3"></i>
                                                            <span>Smart Compose</span>
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a href="javascript:void(0)" class="dropdown-item">
                                                            <i class="feather-feather me-3"></i>
                                                            <span>Manage Signature</span>
                                                        </a>
                                                    </li>
                                                </ul>
                                            </div>
                                            <a href="javascript:void(0);" data-bs-dismiss="modal">
                                                <span class="btn btn-icon" data-bs-toggle="tooltip"
                                                    data-bs-trigger="hover" title="Delete Message">
                                                    <i class="feather-x"></i>
                                                </span>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="profile-details mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-between">
                                    {{-- <h5 class="fw-bold mb-0">Scheduled Emails:</h5> --}}
                                </div>
                            </div>
                        </div>


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

    </div>
    <!-- [ Main Content ] end -->
@endsection
@section('modals')
    <!-- Closed WON Modal -->
    <div class="modal fade" id="closedWonModal" tabindex="-1" aria-labelledby="closedWonModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form action="{{ route('won-lost.storeOrUpdate') }}" method="POST">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="closedWonModalLabel">Closed WON</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Hidden ID field for update -->
                        <input type="hidden" name="ticket_id" value="{{ $ticket->id }}">

                        <input type="hidden" name="id" value="{{ $won->first()->id ?? old('id') }}">
                        <input type="hidden" name="status" value="WON">

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="finalProposal" class="form-label">Final Proposal</label>
                                <select class="form-select" name="final_proposal" id="finalProposal">
                                    <option value="none"
                                        {{ ($won->first()->final_proposal ?? old('final_proposal')) == 'none' ? 'selected' : '' }}>
                                        None
                                    </option>
                                    <option value="mark"
                                        {{ ($won->first()->final_proposal ?? old('final_proposal')) == 'mark' ? 'selected' : '' }}>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        {{ ($won->first()->final_proposal ?? old('final_proposal')) == 'completed' ? 'selected' : '' }}>
                                        Completed</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="finalQuotation" class="form-label">Final Quotation</label>
                                <select class="form-select" name="final_quotation" id="finalQuotation">
                                    <option value="none"
                                        {{ ($won->first()->final_quotation ?? old('final_quotation')) == 'none' ? 'selected' : '' }}>
                                        None
                                    </option>
                                    <option value="mark"
                                        {{ ($won->first()->final_quotation ?? old('final_quotation')) == 'mark' ? 'selected' : '' }}>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        {{ ($won->first()->final_quotation ?? old('final_quotation')) == 'completed' ? 'selected' : '' }}>
                                        Completed</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="finalInvoice" class="form-label">Final Invoice</label>
                                <select class="form-select" name="final_invoice" id="finalInvoice">
                                    <option value="none"
                                        {{ ($won->first()->final_invoice ?? old('final_invoice')) == 'none' ? 'selected' : '' }}>
                                        None
                                    </option>
                                    <option value="mark"
                                        {{ ($won->first()->final_invoice ?? old('final_invoice')) == 'mark' ? 'selected' : '' }}>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        {{ ($won->first()->final_invoice ?? old('final_invoice')) == 'completed' ? 'selected' : '' }}>
                                        Completed</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="closedDate" class="form-label">Closed Date</label>
                                <input type="date" class="form-control" name="closed_date" id="closedDate"
                                    value="{{ $won->first()->closed_date ?? old('closed_date') }}">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="deliveryDate" class="form-label">Delivery or Implementation Date</label>
                                <input type="date" class="form-control" name="delivery_date" id="deliveryDate"
                                    value="{{ $won->first()->delivery_date ?? old('delivery_date') }}">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="paymentStatus" class="form-label">Payment Status</label>
                                <select class="form-select" name="payment_status" id="paymentStatus">
                                    <option value="none"
                                        {{ ($won->first()->payment_status ?? old('payment_status')) == 'none' ? 'selected' : '' }}>
                                        None
                                    </option>
                                    <option value="not_paid"
                                        {{ ($won->first()->payment_status ?? old('payment_status')) == 'not_paid' ? 'selected' : '' }}>
                                        Not Paid</option>
                                    <option value="advance_paid"
                                        {{ ($won->first()->payment_status ?? old('payment_status')) == 'advance_paid' ? 'selected' : '' }}>
                                        Advance Paid
                                    </option>
                                    <option value="paid"
                                        {{ ($won->first()->payment_status ?? old('payment_status')) == 'paid' ? 'selected' : '' }}>
                                        Paid
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="paymentMethod" class="form-label">Payment Method <span class="text-danger">*</span></label>
                                <input class="form-control" name="payment_method" id="paymentMethod" maxlength="100" required
                                    value="{{ $won->first()->payment_method ?? old('payment_method') }}" placeholder="e.g. Bank transfer">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="sentFeedback" class="form-label">Customer Feedback Sent <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="sent_feedback" id="sentFeedback" rows="3" required>{{ $won->first()->sent_feedback ?? old('sent_feedback') }}</textarea>
                            </div>
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Closed LOST Modal -->
    <div class="modal fade" id="closedLostModal" tabindex="-1" aria-labelledby="closedLostModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form action="{{ route('won-lost.storeOrUpdate') }}" method="POST">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="closedLostModalLabel">Closed LOST</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Hidden ID field for update -->
                        <input type="hidden" name="ticket_id" value="{{ $ticket->id }}">

                        <input type="hidden" name="id" value="{{ $lost->first()->id ?? old('id') }}">
                        <input type="hidden" name="status" value="LOST">

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="lostStage" class="form-label">Lost Stage</label>
                                <select class="form-select" name="lost_stage" id="lostStage">
                                    <option value="lost"
                                        {{ ($lost->first()->lost_stage ?? old('lost_stage')) == 'lost' ? 'selected' : '' }}>
                                        Lost
                                    </option>
                                    <option value="not_qualified"
                                        {{ ($lost->first()->lost_stage ?? old('lost_stage')) == 'not_qualified' ? 'selected' : '' }}>
                                        Not-Qualified</option>
                                    <option value="contacted_future"
                                        {{ ($lost->first()->lost_stage ?? old('lost_stage')) == 'contacted_future' ? 'selected' : '' }}>
                                        Contacted in Future
                                    </option>
                                    <option value="competition"
                                        {{ ($lost->first()->lost_stage ?? old('lost_stage')) == 'competition' ? 'selected' : '' }}>
                                        Competition</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="lostDate" class="form-label">Lost Date</label>
                                <input type="date" class="form-control" name="lost_date" id="lostDate"
                                    value="{{ $lost->first()->lost_date ?? old('lost_date') }}">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="lostReason" class="form-label">Lost Reason</label>
                            <textarea class="form-control" name="lost_reason" id="lostReason" rows="3">{{ $lost->first()->lost_reason ?? old('lost_reason') }}</textarea>
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

@endsection
@section('scripts')
    @include('ticket.partials.workflow-history')

    <script>
        // jQuery to handle submenu toggling
        $(document).ready(function() {
            $('.dropdown-submenu > a').on('click', function(e) {
                var $submenu = $(this).next('ul');
                if ($submenu.is(':visible')) {
                    $submenu.slideUp();
                } else {
                    $submenu.stop(true, true).slideDown();
                }
                e.stopPropagation();
                e.preventDefault(); // Prevent closing of the parent dropdown
            });
        });

        // Handle stage status change when a new option is selected from the dropdown
        document.querySelectorAll('.stage-status-select').forEach(select => {
            select.addEventListener('change', function() {
                const stageId = this.dataset.stageId;
                const ticketId = this.dataset.ticketId;
                const selectedStatus = this.value;

                let stageStatus = 1; // Default 'None'
                if (selectedStatus === 'Mark') {
                    stageStatus = 2; // Mark
                } else if (selectedStatus === 'Completed') {
                    stageStatus = 3; // Completed
                }

                // Send the AJAX request to update the stage_status
                fetch('{{ route('update.ticket.stage.status') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        },
                        body: JSON.stringify({
                            ticket_id: ticketId,
                            stage_id: stageId,
                            stage_status: stageStatus,
                        }),
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Refresh the page after a successful update
                            location.reload();
                        } else {
                            alert('Failed to update stage status.');
                        }
                    });
            });
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log("Script is running!");

            $('.update-stage').select2();
            $('.update-stage').next('.select2').css({
                'width': 'auto',
                'min-width': '200px'
            });


            $('.update-stage').on('change', function() {
                const ticketId = $(this).data('id');
                const stageId = $(this).val();

                if (ticketId && stageId) {
                    fetch(`/tickets/${ticketId}/update-ticket-stage`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                            },
                            body: JSON.stringify({
                                stage_id: stageId,
                            }),
                        })
                        .then(response => {
                            if (!response.ok) throw new Error('Failed to update stage');
                            return response.json();
                        })
                        .then(data => {
                            console.log("Response received:", data.message);
                            location.reload();
                        })
                        .catch(error => {
                            console.error("Error:", error);
                        });
                } else {
                    console.warn("Ticket ID or Stage ID is missing!");
                }
            });
        });
    </script>
@endsection
