@extends('layouts.app')

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

@section('content')
    @include('shared.crm-professional-ui')
    <!-- [ page-header ] start -->
    <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">Deal Profile</h5>
                <small class="text-muted d-none d-lg-block">Deal #{{ str_pad((string) $deal->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('share_deals')
                        <x-internal-share-button :url="route('deals.view', ['id' => $deal->id])"
                            :title="'Deal: '.$deal->name" />
                    @endcan
                    <a href="{{ route('deals-create') }}" class="btn btn-primary">
                        <i class="feather-plus me-2"></i>
                        <span>Create Deal</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 deal-profile-page">

        <x-campaign-conversion-attribution :record="$deal" />

        <div class="deal-profile-layout">


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

                <div class="deal-profile-sidebar-head">
                    <div class="d-flex align-items-center gap-3">
                        <span class="deal-profile-sidebar-icon"><i class="feather-layout"></i></span>
                        <div class="min-w-0">
                            <div class="fw-bold text-dark">Deal Workspace</div>
                            <small class="text-muted">Profile navigation</small>
                        </div>
                    </div>
                </div>

                <div class="content-sidebar-body">
                    <ul class="nav flex-column nxl-content-sidebar-item customers-nav-tabs sidebar-style deal-profile-tabs" 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="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="accountsDetailsTabLink" data-bs-toggle="tab"
                                data-bs-target="#accountsDetailsTab" role="tab" aria-controls="accountsDetailsTab"
                                aria-selected="false">
                                <i class="feather-user"></i>
                                <span>Accounts Details</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="tradeDetailsTabLink" data-bs-toggle="tab"
                                data-bs-target="#tradeDetailsTab" role="tab" aria-controls="tradeDetailsTab"
                                aria-selected="false">
                                <i class="feather-briefcase"></i>
                                <span>Trade Details</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="filesTabLink" data-bs-toggle="tab"
                                data-bs-target="#filesTab" role="tab" aria-controls="filesTab">
                                <i class="feather-file"></i>
                                <span>Files</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="reportingTabLink" data-bs-toggle="tab"
                                data-bs-target="#reportingTab" role="tab" aria-controls="reportingTab"
                                aria-selected="false">
                                <i class="feather-bar-chart-2"></i>
                                <span>Reporting (with team)</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="competitorsTabLink" data-bs-toggle="tab"
                                data-bs-target="#competitorsTab" role="tab" aria-controls="competitorsTab"
                                aria-selected="false">
                                <i class="feather-users"></i>
                                <span>Competitors</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="projectsTabLink" data-bs-toggle="tab"
                                data-bs-target="#projectsTab" role="tab" aria-controls="projectsTab"
                                aria-selected="false">
                                <i class="feather-layers"></i>
                                <span>Projects</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="caseTabLink" data-bs-toggle="tab"
                                data-bs-target="#caseTab" role="tab" aria-controls="caseTab" aria-selected="false">
                                <i class="feather-clipboard"></i>
                                <span>Case</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="closingDetailsTabLink"
                                data-bs-toggle="tab" data-bs-target="#closingDetailsTab" role="tab"
                                aria-controls="closingDetailsTab" aria-selected="false">
                                <i class="feather-check-square"></i>
                                <span>Closing Details</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="surveyTabLink" data-bs-toggle="tab"
                                data-bs-target="#surveyTab" role="tab" aria-controls="surveyTab"
                                aria-selected="false">
                                <i class="feather-edit"></i>
                                <span>Survey</span>
                            </a>
                        </li>
                    </ul>




                </div>
            </div>

            <div class="deal-profile-content">

                <div class="card border-top-0 deal-profile-card">
                    <div class="card stretch stretch-full border-0 mb-0">
                        @php
                            $dealStageName = \App\Models\DealStage::find($deal->stage_id)?->name ?? 'New Deal';
                            $dealContact = $deal->contact ?: \App\Models\Contact::find($deal->contact_id);
                            $dealContactName = trim(($dealContact->first_name ?? '').' '.($dealContact->last_name ?? ''));
                            $dealCompanyName = \App\Models\Company::find($deal->company_id)->name ?? $deal->accounts->first()?->account_name ?? 'No company';
                            $dealCreatedDate = $deal->create_date ?: $deal->created_at;
                            $dealIsClosed = in_array((int) $deal->stage_id, [9, 10], true);
                        @endphp
                        <div class="card-body deal-profile-hero">
                            <div class="d-flex flex-column flex-lg-row align-items-lg-start justify-content-between gap-4">
                                <div class="d-flex align-items-start gap-3 min-w-0">
                                    <span class="deal-profile-avatar">{{ strtoupper(substr($deal->name ?: 'DL', 0, 2)) }}</span>
                                    <div class="min-w-0">
                                        <div class="deal-profile-eyebrow mb-1">Deal #{{ str_pad((string) $deal->id, 4, '0', STR_PAD_LEFT) }} · Created {{ optional($dealCreatedDate)->format('d M Y') ?? 'Not set' }}</div>
                                        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
                                            <h4 class="deal-profile-title mb-0 text-truncate">{{ $deal->name ?: 'Untitled Deal' }}</h4>
                                            <span class="badge deal-current-stage-label {{ (int) $deal->stage_id === 9 ? 'bg-success text-white' : ((int) $deal->stage_id === 10 ? 'bg-danger text-white' : 'bg-soft-primary text-primary') }}"
                                                data-current-stage="{{ $deal->stage_id }}">
                                                {{ $dealStageName }}{{ $dealIsClosed ? ' · Completed' : '' }}
                                            </span>
                                        </div>
                                        <div class="deal-profile-contact">
                                            {{ $dealContactName ?: 'No contact name' }}
                                            @if ($deal->deal_type) · {{ ucfirst($deal->deal_type) }} @endif
                                        </div>
                                        <div class="deal-profile-facts">
                                            <span class="deal-profile-fact"><i class="feather-phone"></i>{{ $deal->contactPhones->first()?->phone ?: 'No phone' }}</span>
                                            <span class="deal-profile-fact"><i class="feather-briefcase"></i>{{ $dealCompanyName }}</span>
                                            <span class="deal-profile-fact"><i class="feather-dollar-sign"></i>{{ $deal->currency_name }} {{ number_format((float) $deal->estimate_amount, 2) }}</span>
                                            <span class="deal-profile-fact"><i class="feather-calendar"></i>{{ optional($deal->closing_date)->format('d M Y') ?? 'No close date' }}</span>
                                        </div>
                                        <div class="deal-profile-quick-stats">
                                            <span class="deal-profile-quick-stat"><small>Owner</small><strong>{{ $deal->assignedUser?->name ?: 'Not assigned' }}</strong></span>
                                            <span class="deal-profile-quick-stat"><small>Priority</small><strong>{{ $deal->priority?->name ?: 'Not assigned' }}</strong></span>
                                            <span class="deal-profile-quick-stat"><small>Forecast</small><strong>{{ $deal->currency_name }} {{ number_format((float) $deal->forecast_value, 2) }}</strong></span>
                                        </div>
                                        <div class="mt-3">
                                            <div class="dropdown">
                                                <a class="btn btn-light-brand dropdown-toggle" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 10">
                                                    <i class="feather-activity me-2"></i>Activities
                                                </a>
                                                <div class="dropdown-menu wd-300">
                                                    <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>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="deal-profile-status-panel">
                                    <label class="form-label mb-2">Deal Status</label>
                                    @if (in_array((int) $deal->stage_id, [9, 10], true))
                                        <div class="d-flex align-items-center gap-2 deal-closed-actions">
                                            <span class="badge deal-closed-badge {{ (int) $deal->stage_id === 9 ? 'deal-closed-badge-won' : 'deal-closed-badge-lost' }} fs-6 px-3 py-2">
                                                <i class="{{ (int) $deal->stage_id === 9 ? 'feather-check-circle' : 'feather-x-circle' }} me-1"></i>
                                                {{ $stages->firstWhere('id', $deal->stage_id)?->name ?? ((int) $deal->stage_id === 9 ? 'Closed Won' : 'Closed Lost') }} · Completed
                                            </span>
                                            @if ($canReopen)
                                                <button type="button" class="btn btn-reopen-deal"
                                                    data-bs-toggle="modal" data-bs-target="#reopenDealModal">
                                                    <i class="feather-rotate-ccw me-1"></i>Reopen Deal
                                                </button>
                                            @endif
                                        </div>
                                        <small class="text-muted d-block mt-2">Status is locked until this Deal is reopened.</small>
                                    @else
                                        @php
                                            $allowedNextStageIds = $allowedStageTransitions->get((int) $deal->stage_id, collect());
                                        @endphp
                                        <select class="form-control update-stage" data-id="{{ $deal->id }}"
                                            data-current-stage="{{ $deal->stage_id }}"
                                            data-select2-selector="status"
                                            @disabled($deal->closure_approval_status === 'pending')>
                                        @foreach ($stages as $stage)
                                            <option value="{{ $stage->id }}" data-bg="bg-success"
                                                @selected($deal->stage_id == $stage->id)
                                                @disabled((int) $stage->id !== (int) $deal->stage_id && ! $allowedNextStageIds->contains((int) $stage->id))>
                                                {{ $stage->name }}
                                            </option>
                                        @endforeach
                                        </select>
                                        <small class="text-muted d-block mt-2"><i class="feather-info me-1"></i>Updates the lifecycle flow automatically.</small>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    @if ($deal->closure_approval_status)
                        <div class="px-4 pb-4">
                            <div class="alert {{ $deal->closure_approval_status === 'pending' ? 'alert-warning' : ($deal->closure_approval_status === 'approved' ? 'alert-success' : 'alert-danger') }} mb-0">
                                <div class="d-flex align-items-center justify-content-between gap-3 flex-wrap">
                                    <div>
                                        <strong>Closure Approval: {{ ucfirst($deal->closure_approval_status) }}</strong>
                                        @if ($deal->requested_closure_stage_id)
                                            <div class="small">
                                                Requested status:
                                                {{ \App\Models\DealStage::find($deal->requested_closure_stage_id)?->name }}
                                                · Reporting manager:
                                                {{ $deal->assignedUser?->reportingManager?->name ?? 'Management' }}
                                            </div>
                                        @endif
                                        @if ($deal->closure_approval_note)
                                            <div class="small">Note: {{ $deal->closure_approval_note }}</div>
                                        @endif
                                    </div>

                                    @if (
                                        $deal->closure_approval_status === 'pending' &&
                                        (auth()->user()->is_admin ||
                                            (int) $deal->assignedUser?->reporting_manager_id === (int) auth()->id() ||
                                            auth()->user()->can('approve_deal_closure'))
                                    )
                                        <div class="d-flex gap-2">
                                            <form method="POST" action="{{ route('deals.closure-approval', $deal) }}">
                                                @csrf
                                                <input type="hidden" name="decision" value="approve">
                                                <button class="btn btn-success btn-sm" type="submit">
                                                    <i class="feather-check me-1"></i>Approve & Finalize
                                                </button>
                                            </form>
                                            <form method="POST" action="{{ route('deals.closure-approval', $deal) }}">
                                                @csrf
                                                <input type="hidden" name="decision" value="reject">
                                                <input class="form-control form-control-sm mb-1" name="note"
                                                    placeholder="Rejection reason" required>
                                                <button class="btn btn-danger btn-sm" type="submit">
                                                    <i class="feather-x me-1"></i>Reject
                                                </button>
                                            </form>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    @endif
                    <div class="tab-content">
                        <!-- Activity Tab Content -->
                        <div class="tab-pane fade show active p-4" id="overallTab" role="tabpanel"
                            aria-labelledby="overallTabLink">

                            @include('deals.partials.profile-overview')
                            @if (false) {{-- Legacy flat Deal overview replaced by the professional overview above. --}}

                            <div class="pb-4 deal-stage-scroll">
                                <div class="arrow-steps clearfix">
                                    @foreach ($stages as $stage)
                                        <div class="step {{ $stage->id <= $deal->stage_id ? 'current' : '' }}"
                                            data-stage-id="{{ $stage->id }}">
                                            <span>{{ $stage->name }}</span>
                                        </div>
                                    @endforeach
                                </div>
                            </div>



                            <div class="pt-0 px-4 px-lg-5 pb-5 deal-overview-details">
                                <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-phone"></i>Phone:</span>
                                            @if ($deal->contactPhones->isNotEmpty())
                                                <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                    {{ $deal->contactPhones->first()->phone }}
                                                </a>
                                            @endif
                                        </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-user"></i>Contact Name:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ \App\Models\Contact::find($deal->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-briefcase"></i>Company:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ \App\Models\Company::find($deal->company_id)->name ?? 'No Company' }}
                                            </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">
                                                @if ($deal->contactPhones->isNotEmpty())
                                                    {{ $deal->contactPhones->first()->phone }}
                                                @endif
                                            </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-hash"></i>SIC Code:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $deal->sic_code }}
                                            </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">
                                                {{ $deal->priority->name ?? 'Not Assigned' }}
                                            </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-activity"></i>Deal Type:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $deal->deal_type }}
                                            </a>
                                        </div>
                                    </div>

                                    @if ($deal->parentDeal)
                                        <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-link"></i>Existing Deal:</span>
                                                <a href="{{ route('deals.view', ['id' => $deal->parentDeal->id]) }}"
                                                    class="fw-bold ms-auto">
                                                    {{ $deal->parentDeal->name }} (#{{ $deal->parentDeal->id }})
                                                </a>
                                            </div>
                                        </div>
                                    @endif

                                    <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-dollar-sign"></i>Estimate Amount:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $deal->estimate_amount }}
                                            </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-calendar"></i>Closing Date:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $deal->closing_date }}
                                            </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-repeat"></i>Billing Frequency:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ \App\Models\BillingFrequency::find($deal->billing_frequency_id)->name ?? 'Not Assigned' }}
                                            </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-refresh-cw"></i>Repeat Every:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $deal->billing_frequency_repeat_status }}
                                                {{ strtolower(rtrim($deal->billingFrequency?->type ?? 'period', 's')) }}(s)
                                            </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-clock"></i>Next Billing:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $deal->next_billing_at?->format('d M Y, h:i A') ?? 'Not scheduled' }}
                                            </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-calendar"></i>Create Date & Time:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ optional($deal->create_date)->format('d M Y, h:i A') }}
                                            </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-message-circle"></i>Communication:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">Email, Phone</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endif

                        </div>
                        <!-- Activity Tab Content -->
                        <div class="tab-pane fade p-4" id="activityTab" role="tabpanel"
                            aria-labelledby="activityTabLink">
                            <x-crm-related-workflows module="deals" :record="$deal" />
                            <x-unified-operational-timeline module="deals" :record="$deal" />
                            <a class="btn btn-sm btn-outline-primary mb-3" href="{{ route('related-activity.index', ['deals', $deal->id]) }}">Messages, Follow-ups & To-dos</a>

                            <div class="profile-details mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-end">
                                    <a href="{{ route('schedule-activity-create') }}?dealId={{ $deal->id }}"
                                        class="btn btn-sm btn-light-brand">Create
                                        Activity</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>

                        <div class="tab-pane fade p-4" id="productTab" role="tabpanel"
                            aria-labelledby="productTabLink">
                            <div class="d-flex align-items-center justify-content-between gap-3 flex-wrap mb-4">
                                <div>
                                    <h5 class="fw-bold mb-1">Product Inventory</h5>
                                    <p class="text-muted mb-0">Products and pricing attached only to this deal.</p>
                                </div>
                                <span class="badge bg-soft-primary text-primary fs-12">
                                    {{ $deal->dealProductLine->count() }} linked product(s) - {{ $deal->currency_name }} {{ number_format((float) $deal->estimate_amount, 2) }}
                                </span>
                            </div>

                            @can('update_deals')
                                <form method="POST" action="{{ route('deals.products.store', $deal) }}"
                                    class="border rounded-3 p-3 mb-4 bg-light">
                                    @csrf
                                    <div class="row g-3 align-items-end">
                                        <div class="col-lg-4 col-md-6">
                                            <label class="form-label">Product</label>
                                            <select class="form-control" name="product_id" id="dealProductSelect" required>
                                                <option value="">Select Product</option>
                                                @foreach ($products as $product)
                                                    <option value="{{ $product->id }}"
                                                        data-price="{{ $product->price }}"
                                                        data-discount="{{ $product->discount }}"
                                                        data-tax="{{ $product->tax }}">
                                                        {{ $product->product_name }}{{ $product->stock_quantity !== null ? ' · Stock '.$product->stock_quantity : '' }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-lg-3 col-md-6">
                                            <label class="form-label">Price Book (optional)</label>
                                            <select class="form-control" name="price_book_item_id" id="dealPriceBookItem">
                                                <option value="">Standard product price</option>
                                                @foreach($priceBooks as $book)
                                                    @foreach($book->items as $item)
                                                        <option value="{{ $item->id }}" data-product="{{ $item->product_id }}" data-price="{{ $item->unit_price }}" data-max-discount="{{ $item->max_discount_percent }}">
                                                            {{ $book->name }} · {{ $item->product?->product_name }} · {{ $book->currency }} {{ number_format((float)$item->unit_price,2) }}
                                                        </option>
                                                    @endforeach
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-lg-2 col-md-3">
                                            <label class="form-label">Exchange Rate</label>
                                            <input type="number" class="form-control" name="exchange_rate" min="0.000001"
                                                step="0.000001" value="1" required>
                                        </div>
                                        <div class="col-lg-2 col-md-3">
                                            <label class="form-label">Unit</label>
                                            <select class="form-control" name="unit_id" required>
                                                <option value="1">Pcs</option>
                                                <option value="2">Kg</option>
                                                <option value="3">Ltr</option>
                                            </select>
                                        </div>
                                        <div class="col-lg-2 col-md-3">
                                            <label class="form-label">Quantity</label>
                                            <input type="number" class="form-control" name="quantity" min="0.01"
                                                step="0.01" value="1" required>
                                        </div>
                                        <div class="col-lg-2 col-md-4">
                                            <label class="form-label">Unit Price</label>
                                            <input type="number" class="form-control" name="product_price"
                                                id="dealProductPrice" min="0" step="0.01" required>
                                        </div>
                                        <div class="col-lg-1 col-md-4">
                                            <label class="form-label">Discount %</label>
                                            <input type="number" class="form-control" name="discount"
                                                id="dealProductDiscount" min="0" max="100" step="0.01" value="0">
                                        </div>
                                        <div class="col-lg-4 col-md-6">
                                            <label class="form-label">Discount approval reason</label>
                                            <input class="form-control" name="discount_reason" placeholder="Required when price-book limit is exceeded">
                                        </div>
                                        <div class="col-lg-1 col-md-4">
                                            <label class="form-label">Tax %</label>
                                            <input type="number" class="form-control" name="tax"
                                                id="dealProductTax" min="0" max="100" step="0.01" value="0">
                                        </div>
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="feather-plus me-1"></i>Add Product
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            @endcan

                            <div class="table-responsive border rounded-3">
                                <table class="table table-hover align-middle mb-0 deal-product-table">
                                    <thead class="bg-light">
                                        <tr>
                                            <th>Product</th>
                                            <th>Unit</th>
                                            <th class="text-end">Qty</th>
                                            <th class="text-end">Price</th>
                                            <th class="text-end">Discount</th>
                                            <th class="text-end">Tax</th>
                                            <th class="text-end">Line Total</th>
                                            @can('update_deals')<th class="text-end">Action</th>@endcan
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse ($deal->dealProductLine as $line)
                                            <tr>
                                                <td class="fw-semibold">{{ $line->product?->product_name ?? 'Deleted Product' }}</td>
                                                <td>{{ [1 => 'Pcs', 2 => 'Kg', 3 => 'Ltr'][$line->unit_id] ?? '-' }}</td>
                                                <td class="text-end">{{ number_format((float) $line->quantity, 2) }}</td>
                                                <td class="text-end">{{ $deal->currency_name }} {{ number_format((float) $line->product_price, 2) }}</td>
                                                <td class="text-end">{{ number_format((float) $line->discount, 2) }}%</td>
                                                <td class="text-end">{{ number_format((float) $line->tax, 2) }}%</td>
                                                <td class="text-end fw-bold">{{ $deal->currency_name }} {{ number_format((float) $line->line_total, 2) }}</td>
                                                @can('update_deals')
                                                    <td class="text-end">
                                                        <form method="POST"
                                                            action="{{ route('deals.products.destroy', [$deal, $line]) }}"
                                                            onsubmit="return confirm('Remove this product from the deal?')">
                                                            @csrf @method('DELETE')
                                                            <button type="submit" class="btn btn-sm bg-soft-danger text-danger">
                                                                <i class="feather-trash-2"></i>
                                                            </button>
                                                        </form>
                                                    </td>
                                                @endcan
                                            </tr>
                                            @if($line->discountApproval?->status==='pending')
                                            <tr><td colspan="8"><div class="alert alert-warning py-2 mb-0">
                                                Requested discount {{ $line->requested_discount }}% exceeds the allowed {{ $line->max_discount_snapshot }}%.
                                                <form class="d-inline-flex gap-2 ms-3" method="POST" action="{{ route('deals.discount-approvals.decide',[$deal,$line->discountApproval]) }}">@csrf
                                                    <input class="form-control form-control-sm" name="decision_note" placeholder="Decision note">
                                                    <button class="btn btn-sm btn-success" name="decision" value="approved">Approve</button>
                                                    <button class="btn btn-sm btn-danger" name="decision" value="rejected">Reject</button>
                                                </form>
                                            </div></td></tr>
                                            @endif
                                        @empty
                                            <tr>
                                                <td colspan="8" class="text-center text-muted py-5">
                                                    No products have been added to this deal.
                                                </td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div class="tab-pane fade p-4" id="filesTab" role="tabpanel"
                            aria-labelledby="filesTabLink">
                            <x-crm-file-manager module="deals" :record="$deal" />
                            <div class="d-flex align-items-center justify-content-between gap-3 flex-wrap mb-4">
                                <div>
                                    <h5 class="fw-bold mb-1">Deal Files</h5>
                                    <p class="text-muted mb-0">PDF documents and images uploaded for this deal.</p>
                                </div>
                                <span class="badge bg-soft-primary text-primary">{{ $deal->files->count() }} file(s)</span>
                            </div>

                            @can('update_deals')
                                <form method="POST" action="{{ route('deals.files.store', $deal) }}"
                                    enctype="multipart/form-data" class="border rounded-3 p-3 mb-4 bg-light">
                                    @csrf
                                    <div class="row g-3 align-items-end">
                                        <div class="col-lg-5">
                                            <label class="form-label">Name</label>
                                            <input type="text" class="form-control" name="name"
                                                value="{{ old('name') }}" placeholder="Document name" required>
                                        </div>
                                        <div class="col-lg-5">
                                            <label class="form-label">PDF or Image</label>
                                            <input type="file" class="form-control" name="file"
                                                accept=".pdf,.jpg,.jpeg,.png,.webp,application/pdf,image/*" required>
                                            <small class="text-muted">Maximum file size: 10 MB.</small>
                                        </div>
                                        <div class="col-lg-2">
                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="feather-upload me-1"></i>Upload
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            @endcan

                            <div class="row g-3">
                                @forelse ($deal->files as $file)
                                    <div class="col-xl-6">
                                        <div class="deal-file-card border rounded-3 p-3 h-100">
                                            <div class="d-flex gap-3">
                                                <a href="{{ route('deals.files.view', [$deal, $file]) }}"
                                                    target="_blank" rel="noopener" class="deal-file-preview">
                                                    @if ($file->is_image)
                                                        <img src="{{ route('deals.files.view', [$deal, $file]) }}"
                                                            alt="{{ $file->name }}">
                                                    @else
                                                        <i class="feather-file-text"></i>
                                                        <span>PDF</span>
                                                    @endif
                                                </a>
                                                <div class="min-w-0 flex-grow-1">
                                                    <h6 class="fw-bold mb-1 text-truncate">{{ $file->name }}</h6>
                                                    <div class="small text-muted text-truncate">{{ $file->original_name }}</div>
                                                    <div class="small text-muted mt-2">
                                                        {{ number_format($file->file_size / 1024, 1) }} KB
                                                        · {{ $file->created_at->format('d M Y, h:i A') }}
                                                    </div>
                                                    <div class="small text-muted">
                                                        Uploaded by {{ $file->uploader?->name ?? 'Unknown user' }}
                                                    </div>
                                                    <div class="d-flex gap-2 mt-3">
                                                        <a href="{{ route('deals.files.view', [$deal, $file]) }}"
                                                            target="_blank" rel="noopener"
                                                            class="btn btn-sm btn-light-brand">View</a>
                                                        <a href="{{ route('deals.files.download', [$deal, $file]) }}"
                                                            class="btn btn-sm btn-light">Download</a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                @empty
                                    <div class="col-12">
                                        <div class="alert alert-light border mb-0">No files have been uploaded.</div>
                                    </div>
                                @endforelse
                            </div>
                        </div>

                        <div class="tab-pane fade p-4" id="accountsDetailsTab" role="tabpanel"
                            aria-labelledby="accountsDetailsTabLink">
                            <div class="d-flex align-items-center justify-content-between gap-3 mb-4">
                                <div>
                                    <h5 class="fw-bold mb-1">Linked Accounts</h5>
                                    <p class="text-muted mb-0">Accounts connected to this deal.</p>
                                </div>
                                @can('update_deals')
                                    <a href="{{ route('deals.edit', ['id' => $deal->id]) }}"
                                        class="btn btn-sm btn-light-brand">Manage Accounts</a>
                                @endcan
                            </div>

                            @if ($deal->accounts->isEmpty())
                                <div class="alert alert-light border mb-0">No accounts are linked to this deal.</div>
                            @else
                                <div class="row g-3">
                                    @foreach ($deal->accounts as $account)
                                        <div class="col-xl-6">
                                            <div class="border rounded-3 p-3 h-100">
                                                <div class="d-flex align-items-start justify-content-between gap-3">
                                                    <div>
                                                        <h6 class="fw-bold mb-1">{{ $account->account_name }}</h6>
                                                        <div class="text-muted small">
                                                            {{ $account->account_number ?: 'No account number' }}
                                                        </div>
                                                    </div>
                                                    @if ((int) $deal->account_id === (int) $account->id)
                                                        <span class="badge bg-soft-primary text-primary">Primary</span>
                                                    @endif
                                                </div>
                                                <div class="small text-muted mt-3">
                                                    {{ collect([$account->billing_city, $account->billing_province])->filter()->join(', ') ?: 'No billing location' }}
                                                </div>
                                                <a href="{{ route('account.view', ['id' => $account->id]) }}"
                                                    class="btn btn-sm btn-light-brand mt-3">View Account</a>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            @endif
                        </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={{ $deal->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>

                        @include('deals.partials.lifecycle-tabs')

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

    </div>
    <!-- [ Main Content ] end -->
@endsection

@section('modals')
    @if ($canReopen)
        <div class="modal fade" id="reopenDealModal" tabindex="-1" aria-labelledby="reopenDealModalLabel"
            aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <form method="POST" action="{{ route('deals.reopen', $deal) }}">
                        @csrf
                        <div class="modal-header">
                            <h5 class="modal-title" id="reopenDealModalLabel">Reopen Deal</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p class="text-muted">This returns the Deal to <strong>Awaiting Decision</strong> and enables editing again.</p>
                            <label for="reopenReason" class="form-label fw-semibold">Reason for reopening</label>
                            <textarea class="form-control" id="reopenReason" name="reason" rows="4"
                                required minlength="10" maxlength="2000"
                                placeholder="Explain why this completed Deal must be reopened..."></textarea>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-warning">
                                <i class="feather-rotate-ccw me-1"></i>Reopen Deal
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    @endif

    <!-- 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('deals.close-won', $deal) }}" 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="deal_id" value="{{ $deal->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 <span class="text-danger">*</span></label>
                                <select class="form-select" name="final_proposal" id="finalProposal" required>
                                    <option value="none" @selected(old('final_proposal', $won->first()->final_proposal ?? 'none') === 'none')>None</option>
                                    <option value="mark"
                                        @selected(old('final_proposal', $won->first()->final_proposal ?? 'none') === 'mark')>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        @selected(old('final_proposal', $won->first()->final_proposal ?? 'none') === 'completed')>
                                        Completed</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="finalQuotation" class="form-label">Final Quotation <span class="text-danger">*</span></label>
                                <select class="form-select" name="final_quotation" id="finalQuotation" required>
                                    <option value="none" @selected(old('final_quotation', $won->first()->final_quotation ?? 'none') === 'none')>None</option>
                                    <option value="mark"
                                        @selected(old('final_quotation', $won->first()->final_quotation ?? 'none') === 'mark')>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        @selected(old('final_quotation', $won->first()->final_quotation ?? 'none') === 'completed')>
                                        Completed</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="finalInvoice" class="form-label">Final Invoice <span class="text-danger">*</span></label>
                                <select class="form-select" name="final_invoice" id="finalInvoice" required>
                                    <option value="none" @selected(old('final_invoice', $won->first()->final_invoice ?? 'none') === 'none')>None</option>
                                    <option value="mark"
                                        @selected(old('final_invoice', $won->first()->final_invoice ?? 'none') === 'mark')>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        @selected(old('final_invoice', $won->first()->final_invoice ?? 'none') === 'completed')>
                                        Completed</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="closedDate" class="form-label">Closed Date <span class="text-danger">*</span></label>
                                <input type="datetime-local" class="form-control" name="closed_date" id="closedDate"
                                    value="{{ old('closed_date', $won->first()?->closed_date?->format('Y-m-d\TH:i')) }}" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="deliveryDate" class="form-label">Delivery or Implementation Date <span class="text-danger">*</span></label>
                                <input type="datetime-local" class="form-control" name="delivery_date" id="deliveryDate"
                                    value="{{ old('delivery_date', $won->first()?->delivery_date?->format('Y-m-d\TH:i')) }}" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="paymentStatus" class="form-label">Payment Status <span class="text-danger">*</span></label>
                                <select class="form-select" name="payment_status" id="paymentStatus" required>
                                    @php
                                        $wonPaymentStatus = old('payment_status', $won->first()->payment_status ?? 'none');
                                        $wonPaymentStatus = $wonPaymentStatus === 'paid' ? 'full_paid' : ($wonPaymentStatus === 'not_paid' ? 'none' : $wonPaymentStatus);
                                    @endphp
                                    <option value="none" @selected($wonPaymentStatus === 'none')>None</option>
                                    <option value="advance_paid"
                                        @selected($wonPaymentStatus === 'advance_paid')>
                                        Advance Paid
                                    </option>
                                    <option value="full_paid"
                                        @selected($wonPaymentStatus === 'full_paid')>
                                        Full Paid
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="sentFeedback" class="form-label">Sent Feedback <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="sent_feedback" id="sentFeedback" rows="3" required>{{ old('sent_feedback', $won->first()->sent_feedback ?? '') }}</textarea>
                        </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="deal_id" value="{{ $deal->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">Close Lost Reason <span class="text-danger">*</span></label>
                                <select class="form-select" name="lost_stage" id="lostStage" required>
                                    <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 <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="lost_date" id="lostDate"
                                    value="{{ $lost->first()->lost_date ?? old('lost_date') }}" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="lostReason" class="form-label">Lost Reason <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="lost_reason" id="lostReason" rows="3" required>{{ $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

<style>
    .deal-profile-layout {
        display: grid;
        grid-template-columns: 238px minmax(0, 1fr);
        gap: 20px;
        align-items: start;
    }

    .deal-profile-sidebar {
        position: sticky !important;
        top: 86px;
        width: auto !important;
        min-width: 0;
        height: auto !important;
        max-height: calc(100vh - 115px);
        overflow-y: auto;
        border: 1px solid #e4e9f1;
        border-radius: 16px;
        background: #fff;
        box-shadow: 0 10px 32px rgba(15, 23, 42, .055);
    }

    .deal-profile-sidebar-head {
        padding: 18px;
        border-bottom: 1px solid #edf0f4;
        background: linear-gradient(145deg, #fbfcff, #f4f7ff);
    }

    .deal-profile-sidebar-icon {
        display: inline-flex;
        width: 38px;
        height: 38px;
        align-items: center;
        justify-content: center;
        border-radius: 11px;
        background: #3454d1;
        color: #fff;
        box-shadow: 0 7px 15px rgba(52, 84, 209, .18);
    }

    .deal-profile-content {
        min-width: 0;
    }

    .deal-profile-content > .card,
    .deal-profile-content .card {
        min-width: 0;
    }

    .deal-profile-card {
        border: 1px solid #e4e9f1 !important;
        border-radius: 16px;
        background: #fff;
        box-shadow: 0 12px 36px rgba(15, 23, 42, .06);
        overflow: hidden;
    }

    .deal-profile-hero {
        padding: 26px;
        border-bottom: 1px solid #e9edf3;
        background: radial-gradient(circle at 92% 5%, rgba(52, 84, 209, .09), transparent 30%), linear-gradient(135deg, #fff 0%, #f8faff 100%);
    }

    .deal-profile-avatar {
        display: inline-flex;
        width: 62px;
        height: 62px;
        flex: 0 0 auto;
        align-items: center;
        justify-content: center;
        border-radius: 18px;
        background: linear-gradient(145deg, #3454d1, #5573e8);
        color: #fff;
        font-size: 19px;
        font-weight: 800;
        letter-spacing: .04em;
        box-shadow: 0 10px 22px rgba(52, 84, 209, .24);
    }

    .deal-profile-eyebrow {
        color: #7c8798;
        font-size: 10px;
        font-weight: 750;
        letter-spacing: .08em;
        text-transform: uppercase;
    }

    .deal-profile-title {
        max-width: min(620px, 100%);
        color: #172033;
        font-size: 23px;
        font-weight: 780;
        letter-spacing: -.025em;
    }

    .deal-profile-contact {
        color: #64748b;
        font-size: 13px;
    }

    .deal-profile-facts,
    .deal-profile-quick-stats {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }

    .deal-profile-facts {
        margin-top: 16px;
    }

    .deal-profile-fact {
        display: inline-flex;
        align-items: center;
        gap: 7px;
        min-width: 0;
        min-height: 34px;
        max-width: 260px;
        padding: 7px 10px;
        border: 1px solid #e5e9f0;
        border-radius: 9px;
        background: rgba(255,255,255,.9);
        color: #526072;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .deal-profile-fact i {
        color: #3454d1;
    }

    .deal-profile-quick-stats {
        margin-top: 12px;
    }

    .deal-profile-quick-stat {
        min-width: 112px;
        padding: 9px 11px;
        border: 1px solid #e8ecf3;
        border-radius: 10px;
        background: rgba(255,255,255,.75);
    }

    .deal-profile-quick-stat small {
        display: block;
        margin-bottom: 2px;
        color: #8a95a5;
        font-size: 9px;
        font-weight: 750;
        letter-spacing: .06em;
        text-transform: uppercase;
    }

    .deal-profile-quick-stat strong {
        display: block;
        max-width: 160px;
        overflow: hidden;
        color: #263247;
        font-size: 12px;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .deal-profile-status-panel {
        min-width: 285px;
        padding: 17px;
        border: 1px solid #dfe5ef;
        border-radius: 14px;
        background: rgba(255,255,255,.94);
        box-shadow: 0 8px 20px rgba(15,23,42,.045);
    }

    .deal-profile-status-panel .form-label {
        color: #64748b;
        font-size: 10px;
        font-weight: 700;
        letter-spacing: .05em;
        text-transform: uppercase;
    }

    .deal-profile-status-panel .select2-container {
        width: 100% !important;
    }

    .deal-profile-actions {
        min-width: 280px;
    }

    .deal-profile-actions .select2-container {
        width: 210px !important;
        max-width: 100%;
    }

    .deal-closed-actions {
        align-items: stretch !important;
    }

    .deal-closed-badge {
        border-radius: 8px;
        box-shadow: 0 8px 20px rgba(15, 23, 42, 0.12);
    }

    .deal-closed-badge-won {
        background: #14804a !important;
        color: #fff;
    }

    .deal-closed-badge-lost {
        background: #c2410c !important;
        color: #fff;
    }

    .btn-reopen-deal {
        border: 1px solid #f59e0b;
        background: #fff7ed;
        color: #9a3412;
        font-weight: 600;
        border-radius: 8px;
    }

    .btn-reopen-deal:hover,
    .btn-reopen-deal:focus {
        background: #f59e0b;
        border-color: #d97706;
        color: #fff;
    }

    .deal-stage-scroll {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    .deal-stage-scroll .arrow-steps {
        min-width: 980px;
    }

    .deal-product-table {
        min-width: 900px;
    }

    .deal-product-table th {
        white-space: nowrap;
    }

    .deal-file-preview {
        width: 92px;
        height: 92px;
        flex: 0 0 92px;
        border-radius: 8px;
        background: #f3f6fa;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        color: #3454d1;
        font-weight: 700;
        gap: 4px;
    }

    .deal-file-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .deal-file-preview i {
        font-size: 30px;
    }

    .deal-file-card {
        min-width: 0;
    }

    .deal-overview-details > .row {
        row-gap: 12px;
    }

    .deal-overview-details .col-md-6 > .d-flex {
        min-height: 50px;
        padding: 12px 14px;
        gap: 14px;
        border: 1px solid #edf0f4;
        border-radius: 8px;
        background: #fff;
    }

    .deal-overview-details .col-md-6 > .d-flex > :last-child {
        text-align: right;
        overflow-wrap: anywhere;
    }

    @media (max-width: 991.98px) {
        .deal-profile-layout {
            grid-template-columns: minmax(0, 1fr);
            gap: 16px;
        }

        .deal-profile-sidebar {
            position: static !important;
            max-height: none;
            overflow: hidden;
        }

        .deal-profile-sidebar-head {
            display: none;
        }

        .deal-profile-sidebar .content-sidebar-body {
            height: auto !important;
            min-height: 0 !important;
            overflow-x: auto;
            padding-bottom: 4px;
        }

        .deal-profile-sidebar .deal-profile-tabs.nav.flex-column {
            flex-direction: row !important;
            flex-wrap: nowrap;
            width: max-content;
            min-width: 100%;
        }

        .deal-profile-tabs .nav-item {
            flex: 0 0 auto;
            border-top: 0 !important;
        }

        .deal-profile-tabs .nav-link {
            white-space: nowrap;
            padding: 12px 16px;
        }

        .deal-profile-actions {
            min-width: 0;
        }

        .deal-profile-status-panel {
            width: 100%;
            min-width: 0;
        }
    }

    @media (max-width: 575.98px) {
        .deal-overview-details {
            padding-left: 16px !important;
            padding-right: 16px !important;
        }

        .deal-profile-actions,
        .deal-profile-actions > div {
            width: 100%;
        }

        .deal-profile-actions .select2-container {
            width: 100% !important;
        }
    }
</style>

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const product = document.getElementById('dealProductSelect');
            if (!product) return;

            product.addEventListener('change', function() {
                const option = this.options[this.selectedIndex];
                document.getElementById('dealProductPrice').value = option?.dataset.price || '0';
                document.getElementById('dealProductDiscount').value = option?.dataset.discount || '0';
                document.getElementById('dealProductTax').value = option?.dataset.tax || '0';
            });
            const priceBook = document.getElementById('dealPriceBookItem');
            priceBook?.addEventListener('change', function() {
                const option = this.options[this.selectedIndex];
                if (!option?.dataset.product) return;
                product.value = option.dataset.product;
                document.getElementById('dealProductPrice').value = option.dataset.price;
                document.getElementById('dealProductDiscount').max = option.dataset.maxDiscount || '0';
                document.getElementById('dealProductDiscount').value = '0';
            });
        });
    </script>
    <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 dealId = this.dataset.dealId;
                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.deal.stage.status') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        },
                        body: JSON.stringify({
                            deal_id: dealId,
                            stage_id: stageId,
                            stage_status: stageStatus,
                        }),
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success || data.approval_status === 'pending') {
                            // Refresh the page after a successful update
                            if (data.message) {
                                window.alert(data.message);
                            }
                            location.reload();
                        } else {
                            alert('Failed to update Deal Status.');
                        }
                    });
            });
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log("Script is running!");

            @if ((request('action') === 'won' || old('status') === 'WON') && !in_array((int) $deal->stage_id, [9, 10], true))
                bootstrap.Modal.getOrCreateInstance(document.getElementById('closedWonModal')).show();
            @endif

            @if ((request('action') === 'lost' || old('status') === 'LOST') && !in_array((int) $deal->stage_id, [9, 10], true))
                bootstrap.Modal.getOrCreateInstance(document.getElementById('closedLostModal')).show();
            @endif

            // Ensure Select2 is initialized
            $('.update-stage').select2();

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

            // Attach event listener to Select2 elements
            $('.update-stage').on('change', function() {
                const select = this;
                const dealId = $(select).data('id');
                const stageId = $(select).val();
                const previousStageId = select.dataset.currentStage;

                if (String(stageId) === '9') {
                    $(select).val(previousStageId).trigger('change.select2');
                    bootstrap.Modal.getOrCreateInstance(document.getElementById('closedWonModal')).show();
                    return;
                }

                if (String(stageId) === '10') {
                    $(select).val(previousStageId).trigger('change.select2');
                    bootstrap.Modal.getOrCreateInstance(document.getElementById('closedLostModal')).show();
                    return;
                }

                if (dealId && stageId) {
                    select.disabled = true;
                    fetch(`/deals/${dealId}/update-deal-stage`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                            },
                            body: JSON.stringify({
                                stage_id: stageId,
                            }),
                        })
                        .then(async response => {
                            const data = await response.json().catch(() => ({}));
                            if (!response.ok) {
                                const validationMessage = data.errors
                                    ? Object.values(data.errors).flat().join('\n')
                                    : null;
                                throw new Error(validationMessage || data.message || 'Failed to update Deal Status.');
                            }
                            return data;
                        })
                        .then(data => {
                            if (data.approval_status === 'pending') {
                                window.alert(data.message);
                                window.location.reload();
                                return;
                            }

                            const savedStageId = Number(data.stage_id || stageId);
                            const allowedStageIds = (data.allowed_stage_ids || []).map(Number);

                            document.querySelectorAll('.arrow-steps .step[data-stage-id]').forEach(step => {
                                step.classList.toggle('current', Number(step.dataset.stageId) <= savedStageId);
                            });

                            document.querySelectorAll('.deal-current-stage-label').forEach(label => {
                                label.textContent = data.stage_name || select.options[select.selectedIndex]?.text || '';
                                label.dataset.currentStage = String(savedStageId);
                            });

                            Array.from(select.options).forEach(option => {
                                const optionStageId = Number(option.value);
                                option.disabled = optionStageId !== savedStageId && !allowedStageIds.includes(optionStageId);
                            });

                            select.dataset.currentStage = String(savedStageId);
                            $(select).val(String(savedStageId)).trigger('change.select2');
                            select.disabled = false;
                            window.alert(data.message || 'Deal Status updated successfully.');
                        })
                        .catch(error => {
                            $(select).val(previousStageId).trigger('change.select2');
                            select.disabled = false;
                            window.alert(error.message);
                        });
                }
            });
        });
    </script>
@endsection
