@extends('layouts.app')

@section('title', 'Deals')

@section('content')
    <style>
        .deal-workspace { padding-top: 20px; }
        .deal-list-card { border: 1px solid #e7eaf0; border-radius: 14px; box-shadow: 0 8px 28px rgba(15, 23, 42, .055); overflow: hidden; }
        .deal-list-card .crm-list-filter-toolbar { padding: 18px 20px !important; background: linear-gradient(180deg, #fff 0%, #fbfcfe 100%); }
        #dealServerList { min-width: 2050px; width: 100%; margin-bottom: 0; }
        #dealServerList thead th { padding: 13px 14px; border-bottom: 1px solid #e8ebf0; background: #f7f9fc; color: #64748b; font-size: 11px; font-weight: 700; letter-spacing: .055em; text-transform: uppercase; }
        #dealServerList tbody td { padding: 15px 14px; border-color: #eef1f5; color: #334155; vertical-align: middle; }
        #dealServerList tbody tr { transition: background-color .16s ease, box-shadow .16s ease; }
        #dealServerList tbody tr:hover { background: #fafcff; box-shadow: inset 3px 0 0 #3454d1; }
        #dealServerList .crm-list-actions-column { min-width: 190px; }
        #dealServerList .deal-table-stage-select { min-width: 185px; }

        .deal-name-avatar, .deal-owner-avatar { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; font-weight: 700; }
        .deal-name-avatar { width: 38px; height: 38px; border-radius: 10px; background: #eef2ff; color: #3454d1; font-size: 13px; }
        .deal-owner-avatar { width: 32px; height: 32px; border-radius: 50%; background: #ecfdf5; color: #16845b; font-size: 11px; }
        .deal-primary-link { color: #172033 !important; font-weight: 650; line-height: 1.3; }
        .deal-primary-link:hover { color: #3454d1 !important; }
        .deal-meta { color: #94a3b8; font-size: 11px; }
        .deal-activity-card { width: 230px; padding: 10px 12px; border: 1px solid #e9edf3; border-radius: 10px; background: #fbfcfe; }
        .deal-activity-card .progress { background: #e8edf5; }
        .deal-status-column { min-width: 205px; white-space: normal; }
        .deal-status-locked { padding: 10px; border: 1px solid #e9edf3; border-radius: 10px; background: #fbfcfe; }
        .deal-multi-values { display: flex; align-items: center; gap: 5px; flex-wrap: wrap; max-width: 260px; white-space: normal; }
        .deal-multi-value { display: inline-flex; align-items: center; gap: 5px; padding: 4px 8px; border-radius: 999px; color: #475569; background: #f1f5f9; font-size: 10px; font-weight: 650; }
        .deal-comments { display: block; max-width: 260px; overflow: hidden; text-overflow: ellipsis; color: #64748b; }
        .deal-money { color: #1f3a8a; font-weight: 750; }
        .deal-probability { display: inline-flex; min-width: 52px; justify-content: center; padding: 4px 8px; border-radius: 8px; color: #3454d1; background: #eef2ff; font-weight: 750; }
        .deal-row-actions .avatar-text { border: 1px solid #e5e9f0; border-radius: 9px; background: #fff; color: #64748b; box-shadow: none; transition: all .15s ease; }
        .deal-row-actions .avatar-text:hover { border-color: #c8d2f0; background: #f2f5ff; color: #3454d1; transform: translateY(-1px); }
        .deal-empty-state { padding: 60px 24px !important; text-align: center; }
        .deal-empty-state-icon { display: inline-flex; width: 52px; height: 52px; align-items: center; justify-content: center; margin-bottom: 12px; border-radius: 14px; background: #eef2ff; color: #3454d1; font-size: 22px; }
        @media (max-width: 767.98px) {
            .deal-workspace { padding-top: 12px; }
            .deal-list-card { border-radius: 10px; }
        }
    </style>

    <!-- [ page-header ] start -->
    <div class="page-header">
        <div class="page-header-left d-flex align-items-center">
            <div class="page-header-title">
                <h5 class="mb-1">Deals</h5>
                <small class="text-muted d-none d-lg-block">Track opportunities, value and sales progress</small>
            </div>
        </div>
        <div class="page-header-right ms-auto">
            <div class="page-header-right-items">
                <div class="d-flex d-md-none">
                    <a href="javascript:void(0)" class="page-header-right-close-toggle">
                        <i class="feather-arrow-left me-2"></i>
                        <span>Back</span>
                    </a>
                </div>
                <div class="d-flex align-items-center gap-2 page-header-right-items-wrapper">
                    <a href="javascript:void(0);" class="btn btn-icon btn-light-brand" data-bs-toggle="collapse"
                        data-bs-target="#collapseOne">
                        <i class="feather-bar-chart"></i>
                    </a>
                    <div class="dropdown">
                        <a class="btn btn-icon btn-light-brand" data-bs-toggle="dropdown" data-bs-offset="0, 10"
                            data-bs-auto-close="outside">
                            <i class="feather-eye"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a href="{{ route('deals') }}" class="dropdown-item active">
                                <i class="feather-list me-3"></i>
                                <span>Table View</span>
                            </a>
                            <a href="{{ route('deals-dashboard') }}" class="dropdown-item">
                                <i class="feather-grid me-3"></i>
                                <span>Dashboard View</span>
                            </a>
                        </div>
                    </div>
                    <div class="dropdown">
                        <a class="btn btn-icon btn-light-brand" data-bs-toggle="dropdown" data-bs-offset="0, 10"
                            data-bs-auto-close="outside">
                            <i class="feather-paperclip"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a href="javascript:void(0);" class="dropdown-item">
                                <i class="bi bi-filetype-pdf me-3"></i>
                                <span>PDF</span>
                            </a>
                            <a href="javascript:void(0);" class="dropdown-item">
                                <i class="bi bi-filetype-csv me-3"></i>
                                <span>CSV</span>
                            </a>
                            <a href="javascript:void(0);" class="dropdown-item">
                                <i class="bi bi-filetype-xml me-3"></i>
                                <span>XML</span>
                            </a>
                            <a href="javascript:void(0);" class="dropdown-item">
                                <i class="bi bi-filetype-txt me-3"></i>
                                <span>Text</span>
                            </a>
                            <a href="javascript:void(0);" class="dropdown-item">
                                <i class="bi bi-filetype-exe me-3"></i>
                                <span>Excel</span>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="javascript:void(0);" class="dropdown-item">
                                <i class="bi bi-printer me-3"></i>
                                <span>Print</span>
                            </a>
                        </div>
                    </div>
                    @if((int) auth()->user()->is_admin === 1 || auth()->user()->can('create_deals'))
                    <a href="{{ route('deals-create') }}" class="btn btn-primary">
                        <i class="feather-plus me-2"></i>
                        <span>Create Deal</span>
                    </a>
                    @endif
                </div>
            </div>
            <div class="d-md-none d-flex align-items-center">
                <a href="javascript:void(0)" class="page-header-right-open-toggle">
                    <i class="feather-align-right fs-20"></i>
                </a>
            </div>
        </div>
    </div>
    <div id="collapseOne" class="accordion-collapse collapse page-header-collapse">
        <div class="accordion-body pb-2">
            <div class="row">
                <div class="col-xxl-3 col-md-6">
                    <div class="card stretch stretch-full">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="avatar-text avatar-xl rounded">
                                        <i class="feather-users"></i>
                                    </div>
                                    <a href="javascript:void(0);" class="fw-bold d-block">
                                        <span class="text-truncate-1-line">Month Deal Won</span>
                                        <span class="fs-24 fw-bolder d-block">{{ $monthDealWon }}</span>
                                    </a>
                                </div>
                                <!-- <div class="badge bg-soft-success text-success">
                                    <i class="feather-arrow-up fs-10 me-1"></i>
                                    <span>36.85%</span>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-md-6">
                    <div class="card stretch stretch-full">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="avatar-text avatar-xl rounded">
                                        <i class="feather-user-check"></i>
                                    </div>
                                    <a href="javascript:void(0);" class="fw-bold d-block">
                                        <span class="text-truncate-1-line">Month Deal Lost</span>
                                        <span class="fs-24 fw-bolder d-block">{{ $monthDealLost }}</span>
                                    </a>
                                </div>
                                <!-- <div class="badge bg-soft-danger text-danger">
                                    <i class="feather-arrow-down fs-10 me-1"></i>
                                    <span>24.56%</span>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-md-6">
                    <div class="card stretch stretch-full">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="avatar-text avatar-xl rounded">
                                        <i class="feather-user-plus"></i>
                                    </div>
                                    <a href="javascript:void(0);" class="fw-bold d-block">
                                        <span class="text-truncate-1-line">Year Deal Won</span>
                                        <span class="fs-24 fw-bolder d-block">{{ $yearDealWon }}</span>
                                    </a>
                                </div>
                                <!-- <div class="badge bg-soft-success text-success">
                                    <i class="feather-arrow-up fs-10 me-1"></i>
                                    <span>33.29%</span>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-md-6">
                    <div class="card stretch stretch-full">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="avatar-text avatar-xl rounded">
                                        <i class="feather-user-minus"></i>
                                    </div>
                                    <a href="javascript:void(0);" class="fw-bold d-block">
                                        <span class="text-truncate-1-line">Year Deal Lost</span>
                                        <span class="fs-24 fw-bolder d-block">{{ $yearDealLost }}</span>
                                    </a>
                                </div>
                                <!-- <div class="badge bg-soft-danger text-danger">
                                    <i class="feather-arrow-down fs-10 me-1"></i>
                                    <span>42.47%</span>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- [ page-header ] end -->
    <!-- [ Main Content ] start -->
    <div class="main-content deal-workspace">
        <div class="row">
            <div class="col-lg-12">
                <div class="card stretch stretch-full deal-list-card">
                    <div class="card-body p-0">
                        <x-server-list-toolbar form-id="deal-filter-form" title="Filter Deals"
                            description="Refine opportunities by status, priority and date" :total="$dealPaginator->total()" total-label="Deals"
                            placeholder="Search deals by name, source, or type" :filters="[
                            'status'=>['label'=>'Record status','options'=>['active'=>'Active','inactive'=>'Inactive']],
                            'stage_id'=>['label'=>'Deal status','options'=>$stages->pluck('name','id')->all()],
                            'priority_id'=>['label'=>'Priority','options'=>$priorities->pluck('name','id')->all()],
                            'date_from'=>['label'=>'Created from','type'=>'date'],'date_to'=>['label'=>'Created to','type'=>'date'],
                        ]" />
                        <div class="table-responsive crm-list-table-scroll">
                            <table class="table table-hover crm-list-table" id="dealServerList">
                                <thead>
                                    <tr>
                                        <th class="wd-30">
                                            <div class="btn-group mb-1">
                                                <div class="custom-control custom-checkbox ms-1">
                                                    <input type="checkbox" class="custom-control-input"
                                                        id="checkAllCustomer">
                                                    <label class="custom-control-label" for="checkAllCustomer"></label>
                                                </div>
                                            </div>
                                        </th>
                                        <th>Deal Name</th>
                                        <th class="deal-status-column">Stage</th>
                                        <th>Deal Owner</th>
                                        <th>Deal Value</th>
                                        <th>Contacts</th>
                                        <th>Accounts</th>
                                        <th>Expected Close Date</th>
                                        <th>Close Probability</th>
                                        <th>Forecast Value</th>
                                        <th>Last Interaction</th>
                                        <th>Comments</th>
                                        <th class="text-end crm-list-actions-column">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @forelse ($deals as $deal)
                                        @php
                                            $isClosedDeal = in_array((int) $deal->stage_id, [9, 10], true);
                                            $dealContacts = $deal->contacts->whenEmpty(fn () => $deal->contact ? collect([$deal->contact]) : collect());
                                            $dealAccounts = $deal->accounts;
                                            $currencyCode = substr($deal->currency_name, 0, 3);
                                            $dealProgress = max(0, min(100, (int) ($deal->close_probability ?? 0)));
                                        @endphp
                                        <tr class="single-item">
                                            <td>
                                                <div class="item-checkbox ms-1">
                                                    <div class="custom-control custom-checkbox">
                                                        <input type="checkbox" class="custom-control-input checkbox"
                                                            id="checkBox_{{ $deal->id }}">
                                                        <label class="custom-control-label"
                                                            for="checkBox_{{ $deal->id }}"></label>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center gap-3" style="min-width: 220px;">
                                                    <span class="deal-name-avatar">
                                                        {{ strtoupper(substr($deal->name ?: 'D', 0, 2)) }}
                                                    </span>
                                                    <div class="min-w-0">
                                                        <a href="{{ route('deals.view') }}?id={{ $deal->id }}"
                                                            class="deal-primary-link d-block text-truncate">
                                                            {{ $deal->name ?: 'Untitled Deal' }}
                                                        </a>
                                                        <span class="deal-meta">Deal #{{ str_pad((string) $deal->id, 4, '0', STR_PAD_LEFT) }}</span>
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="deal-status-column">
                                                @if (! $isClosedDeal && auth()->user()->can('update_deals'))
                                                    <select class="form-select form-select-sm deal-table-stage-select"
                                                        data-deal-id="{{ $deal->id }}"
                                                        data-current-stage="{{ $deal->stage_id }}"
                                                        aria-label="Change status for {{ $deal->name }}">
                                                        @foreach ($stages as $stage)
                                                            <option value="{{ $stage->id }}"
                                                                @selected((int) $deal->stage_id === (int) $stage->id)>
                                                                {{ $stage->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                @else
                                                    @php
                                                        $dealStageName = $stages->firstWhere('id', $deal->stage_id)?->name ?? 'Unknown';
                                                        $dealStageBadge = (int) $deal->stage_id === 9
                                                            ? 'bg-success text-white'
                                                            : ((int) $deal->stage_id === 10
                                                                ? 'bg-danger text-white'
                                                                : 'bg-soft-primary text-primary');
                                                    @endphp
                                                    @if ($isClosedDeal)
                                                        <div class="deal-status-locked">
                                                            <span class="badge {{ $dealStageBadge }} px-3 py-2">
                                                                @if ((int) $deal->stage_id === 9)
                                                                    <i class="feather-check-circle me-1"></i>
                                                                @elseif ((int) $deal->stage_id === 10)
                                                                    <i class="feather-x-circle me-1"></i>
                                                                @endif
                                                                {{ $dealStageName }} · Completed
                                                            </span>
                                                        </div>
                                                    @else
                                                        <span class="badge {{ $dealStageBadge }}">{{ $dealStageName }}</span>
                                                    @endif
                                                @endif
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center gap-2" style="min-width: 180px;">
                                                    <span class="deal-owner-avatar">{{ strtoupper(substr($deal->assignedUser?->name ?: 'NA', 0, 2)) }}</span>
                                                    <div class="min-w-0">
                                                        <div class="fw-semibold text-dark text-truncate">{{ $deal->assignedUser?->name ?? 'Not Assigned' }}</div>
                                                        <small class="text-muted text-truncate d-block">{{ $deal->assignedUser?->email ?: 'No owner selected' }}</small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td><span class="deal-money">{{ $currencyCode }} {{ number_format((float) ($deal->grand_total ?: $deal->estimate_amount), 2) }}</span></td>
                                            <td><div class="deal-multi-values">@forelse($dealContacts as $contact)<span class="deal-multi-value"><i class="feather-user"></i>{{ trim($contact->first_name.' '.$contact->last_name) ?: 'Contact #'.$contact->id }}</span>@empty<span class="text-muted">—</span>@endforelse</div></td>
                                            <td><div class="deal-multi-values">@forelse($dealAccounts as $account)<span class="deal-multi-value"><i class="feather-home"></i>{{ $account->account_name }}</span>@empty<span class="text-muted">—</span>@endforelse</div></td>
                                            <td>{{ optional($deal->closing_date)->format('d M Y') ?: '—' }}</td>
                                            <td><span class="deal-probability">{{ (int) ($deal->close_probability ?? 0) }}%</span></td>
                                            <td><span class="deal-money">{{ $currencyCode }} {{ number_format((float) ($deal->forecast_value ?? 0), 2) }}</span></td>
                                            <td>
                                                <div class="deal-activity-card">
                                                    <div class="d-flex align-items-start justify-content-between gap-2 mb-2">
                                                        <div class="min-w-0">
                                                            <div class="fw-semibold text-dark text-truncate">{{ $deal->latestActivity?->title ?: 'No interaction yet' }}</div>
                                                            <small class="text-muted">
                                                                {{ optional($deal->latestActivity?->updated_at)->format('M d, Y · H:i') ?: 'Add the first follow-up' }}
                                                            </small>
                                                        </div>
                                                        <span class="badge bg-soft-primary text-primary">{{ $dealProgress }}%</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between small mb-1">
                                                        <span class="fw-semibold">Win likelihood</span>
                                                        <strong class="text-primary">{{ $dealProgress }}%</strong>
                                                    </div>
                                                    <div class="progress ht-6" role="progressbar" aria-label="Deal win likelihood"
                                                        aria-valuenow="{{ $dealProgress }}" aria-valuemin="0" aria-valuemax="100">
                                                        <div class="progress-bar bg-primary" style="width: {{ $dealProgress }}%"></div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td><span class="deal-comments" title="{{ $deal->comments }}">{{ \Illuminate\Support\Str::limit($deal->comments ?: '—', 80) }}</span></td>

                                            <td class="text-end crm-list-actions-column">
                                                <div class="d-inline-flex align-items-center justify-content-end gap-2 deal-row-actions">
                                                    @can('share_deals')
                                                        <x-internal-share-button compact :url="route('deals.view', ['id' => $deal->id])"
                                                            :title="'Deal: '.$deal->name" label="Share Deal" />
                                                    @endcan
                                                    <a href="{{ route('deals.view') }}?id={{ $deal->id }}"
                                                        class="avatar-text avatar-md"
                                                        title="View Deal" aria-label="View Deal">
                                                        <i class="feather feather-eye"></i>
                                                    </a>
                                                    @can('update_deals')
                                                        @unless ($isClosedDeal)
                                                        <a href="{{ route('deals.edit') }}?id={{ $deal->id }}"
                                                            class="avatar-text avatar-md"
                                                            title="Edit Deal" aria-label="Edit Deal">
                                                            <i class="feather feather-edit-3"></i>
                                                        </a>
                                                        @endunless
                                                    @endcan
                                                    @can('delete_deals')
                                                        @unless ($isClosedDeal)
                                                        <form action="{{ route('deals.destroy', $deal->id) }}" method="POST"
                                                            class="d-inline-flex m-0"
                                                            onsubmit="return confirm('Are you sure you want to delete this deal?');">
                                                            @csrf
                                                            @method('DELETE')
                                                            <button type="submit"
                                                                class="avatar-text avatar-md border-0 bg-transparent text-danger p-0"
                                                                title="Delete Deal" aria-label="Delete Deal">
                                                                <i class="feather feather-trash-2"></i>
                                                            </button>
                                                        </form>
                                                        @endunless
                                                    @endcan
                                                </div>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="13" class="deal-empty-state">
                                                <span class="deal-empty-state-icon"><i class="feather-briefcase"></i></span>
                                                <h6 class="fw-bold mb-1">No Deals found</h6>
                                                <p class="text-muted mb-3">Adjust the filters or create a new Deal to keep your sales pipeline moving.</p>
                                                @if((int) auth()->user()->is_admin === 1 || auth()->user()->can('create_deals'))
                                                    <a href="{{ route('deals-create') }}" class="btn btn-sm btn-primary">
                                                        <i class="feather-plus me-1"></i>Create Deal
                                                    </a>
                                                @endif
                                            </td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="px-4 pb-4">{{ $dealPaginator->links() }}</div>
    <!-- [ Main Content ] end -->
@endsection
@section('modals')
    <div class="modal fade" id="addActivity" aria-labelledby="addActivityLabel" aria-hidden="true" x-data>
        <form id="createActivityForm" method="POST" action="/activity/store" class="p-3" enctype="multipart/form-data">
            @csrf
            <input type="hidden" name="activity_type_id" x-bind:value="$store.activity.selectedButton" />

            <div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Activity</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">

                        <!-- Title Field -->
                        <div class="col-lg-16 mb-4">
                            <div class="input-group">
                                <div class="input-group-text"><i class="feather-tag"></i></div>
                                <input type="text" class="form-control" name="title" id="titleInput"
                                    placeholder="Title">
                            </div>
                        </div>


                        <!-- Title Field -->
                        <div class="col-lg-12 mb-4" x-show="([4, 2,].includes($store.activity.selectedButton))"
                            x-transition>
                            <div class="activity-date-time-row d-flex gap-2 align-items-center flex-wrap">
                                <!-- Start Date -->
                                <input type="date" class="form-control flex-grow-1" name="start_date"
                                    placeholder="Dec 9, 2024" />

                                <!-- Start Time -->
                                <input type="time" class="form-control flex-grow-1" name="start_time"
                                    placeholder="h:mm AM" />

                                <span class="align-self-center">-</span>

                                <!-- End Date -->
                                <input type="date" class="form-control flex-grow-1" name="end_date"
                                    placeholder="Dec 9, 2024" />

                                <!-- End Time -->
                                <input type="time" class="form-control flex-grow-1" name="end_time"
                                    placeholder="h:mm AM" />
                            </div>
                        </div>

                        @php
                            $selectedContactId = request('id');
                            $selectedLeadId = request('leadId');
                            $selectedDealId = request('dealId');
                        @endphp
                        <div class="row">
                            <div class="col-lg-6 mb-4">
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <select class="form-control" name="contact_id" id="contactInput">
                                        <option value="">Select
                                            Contact</option>
                                        @foreach ($contacts as $contact)
                                            <option value="{{ $contact->id }}">
                                                {{ $contact->first_name }}
                                            </option>
                                        @endforeach
                                    </select>

                                </div>
                            </div>

                            <input type="hidden" name="deal_id" id="hiddenDealId">


                            <!-- Priority Dropdown -->
                            <div class="col-lg-6 mb-4" x-show="([1,3,4,9].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-award"></i></div>
                                    <select class="form-control" name="priority" id="priorityInput">
                                        <option value="" disabled selected>Priority</option>
                                        @foreach ($priorities as $priority)
                                            <option value="{{ $priority->id }}">{{ $priority->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>







                            {{-- <div class="col-lg-6 mb-4" x-show="([6].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-map-pin"></i></div>
                                    <select class="form-control" name="location" id="locationInput">
                                        <option value="" disabled selected>Select Location</option>
                                        @foreach ($countries as $country)
                                            <option value="{{ $country->id }}">{{ $country->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div> --}}

                            {{-- <div class="col-lg-6 mb-4" x-show="([6,10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-users"></i></div>
                                    <select class="form-control" name="customer" id="customerInput">
                                        <option value="" disabled selected>Select Customer</option>
                                        <option value="1">Customer 1</option>
                                        <option value="2">Customer 2</option>
                                        <option value="3">Customer 3</option>
                                        <option value="4">Customer 4</option>
                                    </select>
                                </div>
                            </div> --}}
                            {{-- <div class="col-lg-6 mb-4" x-show="([6].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-briefcase"></i></div>
                                    <input type="text" class="form-control" name="service" id="serviceInput"
                                        placeholder="Service" />
                                </div>
                            </div> --}}


                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <select class="form-control" name="meeting_integration" id="meetingIntegrationInput">
                                        <option value="" disabled selected>Select Meeting Integration
                                        </option>
                                        @foreach ($meetings as $meeting)
                                            <option value="{{ $meeting->id }}">{{ $meeting->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>



                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <select class="form-control" name="allDayEventStatus" id="allDayEventStatus">
                                        <option value="" disabled selected>All Day Event Status</option>
                                        @foreach ($eventStatuses as $status)
                                            <option value="{{ $status->name }}">{{ $status->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>


                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <input type="text" class="form-control" name="callFrom" id="callFromInput"
                                        placeholder="Call From" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-phone"></i></div>
                                    <input type="text" class="form-control" name="phoneNumber" id="phoneNumberInput"
                                        placeholder="Phone Number" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([1, 3, 4].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-flag"></i></div>
                                    <input type="text" class="form-control" name="regarding" id="regardingInput"
                                        placeholder="Regarding" />
                                </div>
                            </div>


                            {{-- <div class="col-lg-16 mb-4" x-show="([7].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-map-pin"></i></div>
                                    <input type="text" class="form-control" name="address" id="addressInput"
                                        placeholder="Address" />
                                </div>
                            </div>
                            <div class="col-lg-6 mb-4" x-show="([8].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-printer"></i></div>
                                    <input type="text" class="form-control" name="fax" id="faxInput"
                                        placeholder="Fax" />
                                </div>
                            </div> --}}

                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-compass"></i></div>
                                    <input type="text" class="form-control" name="direction" id="directionInput"
                                        placeholder="Direction" />
                                </div>
                            </div>


                            <!-- From Email -->
                            <div class="col-lg-6 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="fromEmailInput" class="form-label">From Email</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-mail"></i></div>
                                    <x-activity-email-sender id="fromEmailInput" />
                                </div>
                            </div>

                            <!-- Email To -->
                            <div class="col-lg-6 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="emailToInput" class="form-label">Email To</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-send"></i></div>
                                    <input type="email" class="form-control" name="email_to" id="emailToInput"
                                        placeholder="Email To" />
                                </div>
                            </div>

                            <!-- Subject -->
                            <div class="col-lg-12 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="subjectInput" class="form-label">Subject</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-align-left"></i></div>
                                    <input type="text" class="form-control" name="subject" id="subjectInput"
                                        placeholder="Subject" />
                                </div>
                            </div>

                            <!-- Email Body -->
                            <div class="col-lg-12 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="emailBodyInput" class="form-label">Email Body</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-file-text"></i></div>
                                    <textarea class="form-control" name="email_body" id="emailBodyInput" rows="5" placeholder="Email Body"></textarea>
                                </div>
                            </div>

                            <!-- Attachment -->
                            <div class="col-lg-12 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="attachmentInput" class="form-label">Attachment</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-paperclip"></i></div>
                                    <input type="file" class="form-control" name="attachment" id="attachmentInput" />
                                </div>
                            </div>

                            <!-- Company Dropdown -->
                            {{-- <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-briefcase"></i></div>
                                    <select class="form-control" name="company" id="companyInput">
                                        <option value="" disabled selected>Select Company</option>
                                        @foreach ($companies as $company)
                                            <option value="{{ $company->id }}">{{ $company->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div> --}}


                            <!-- Owner Dropdown -->
                            <div class="col-lg-6 mb-4">
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <select class="form-control" name="owner" id="ownerInput">
                                        @foreach ($users as $user)
                                            <option value="{{ $user->id }}"
                                                {{ auth()->id() == $user->id ? 'selected' : '' }}>
                                                {{ $user->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>


                            <!-- First Name Field -->
                            {{-- <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <input type="text" class="form-control" name="first_name" id="firstNameInput"
                                        placeholder="First Name" />
                                </div>
                            </div>

                            <!-- Last Name Field -->
                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <input type="text" class="form-control" name="last_name" id="lastNameInput"
                                        placeholder="Last Name" />
                                </div>
                            </div> --}}

                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <input type="text" class="form-control" name="meeting_details"
                                        id="meetingDetailsInput" placeholder="Meeting Details" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-monitor"></i></div>
                                    <input type="text" class="form-control" name="hosting" id="hostingInput"
                                        placeholder="Hosting" />
                                </div>
                            </div>
                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-link"></i></div>
                                    <select class="form-control" name="related_to" id="relatedToInput">
                                        <option value="" disabled selected>Related To</option>
                                        <option value="1">Lead</option>
                                        <option value="2">Contact</option>
                                        <option value="3">Deal</option>
                                        <option value="4">Account</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-refresh-ccw"></i></div>
                                    <select class="form-control" name="repeat_type" id="repeatTypeInput">
                                        <option value="" disabled selected>Select Repeat Type</option>
                                        @foreach ($repeats as $repeat)
                                            <option value="{{ $repeat->id }}">{{ $repeat->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>



                            <div class="col-lg-6 mb-4" x-show="([2,4].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-users"></i></div>
                                    <select class="form-control" name="participants" id="participantsInput">
                                        <option value="" disabled selected>Select Participants</option>
                                        <option value="1">Lead</option>
                                        <option value="2">Contact</option>
                                        <option value="3">Deal</option>
                                        <option value="4">Account</option>
                                        <option value="5">Users</option>
                                        <option value="6">New Invite Account</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Duration Field -->
                            <div class="col-lg-6 mb-4">
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-clock"></i></div>
                                    <input type="text" class="form-control" name="duration" id="durationInput"
                                        placeholder="Duration" />
                                </div>
                            </div>

                            <!-- Due Date Field -->
                            <div class="col-lg-6 mb-4" x-show="([1, 3, 9, 2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <input type="date" class="form-control" name="due_date" id="dueDateInput"
                                        placeholder="Due Date" />
                                </div>
                            </div>

                            {{-- <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-tag"></i></div>
                                    <input type="text" class="form-control" name="promotion_code"
                                        id="promotionCodeInput" placeholder="Promotion Code" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-target"></i></div>
                                    <select class="form-control" name="related_campaign" id="relatedCampaignInput">
                                        <option value="" disabled selected>Related Campaign</option>
                                        <option value="1">Campaign 1</option>
                                        <option value="2">Campaign 2</option>
                                        <option value="3">Campaign 3</option>
                                        <option value="4">Campaign 4</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-code"></i></div>
                                    <input type="text" class="form-control" name="response_code"
                                        id="responseCodeInput" placeholder="Response Code" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-radio"></i></div>
                                    <select class="form-control" name="channel" id="channelInput">
                                        <option value="" disabled selected>Select Channel</option>
                                        <option value="1">Email</option>
                                        <option value="2">SMS</option>
                                        <option value="3">Phone</option>
                                        <option value="4">Social Media</option>
                                        <option value="5">Web</option>
                                        <option value="6">Push Notification</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <!-- Received On Input -->
                                <label for="receivedOnInput" class="form-label">Received On</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <input type="date" class="form-control" name="received_on" id="receivedOnInput"
                                        placeholder="Received On" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <!-- Close By Input -->
                                <label for="closeByInput" class="form-label">Close By</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <input type="date" class="form-control" name="close_by" id="closeByInput"
                                        placeholder="Close By" />
                                </div>
                            </div> --}}

                            <!-- Call From Field -->
                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <input type="text" class="form-control" name="callFrom" id="callFromInput"
                                        placeholder="Call From" />
                                </div>
                            </div>
                            <div class="col-lg-16 mb-4" x-show="([1, 2, 3, 4,].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-file-text"></i></div>
                                    <textarea class="form-control" name="description" id="descriptionInput" placeholder="Description"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>



                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Discard</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="feather-activity me-2"></i>
                            <span>Create Activity</span>
                        </button>
                    </div>

                </div>

            </div>


        </form>
    </div>
@endsection
@section('scripts')


    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.store('activity', {
                selectedButton: null, // Track the currently selected button
                activityTypes: {
                    'call': 1,
                    'meeting': 2,
                    'task': 3,
                    'event': 4,
                    'deadline': 5,
                    'otheractivity': 6,
                    'letter': 7,
                    'fax': 8,
                    'email': 9,
                    'campaign': 10
                },
            });
        });

        document.addEventListener('DOMContentLoaded', function() {

            document.querySelectorAll('.deal-table-stage-select').forEach(function(select) {
                select.addEventListener('change', async function() {
                    const previousStageId = select.dataset.currentStage;
                    const selectedStageId = select.value;
                    const dealId = select.dataset.dealId;

                    if (String(selectedStageId) === '9') {
                        select.value = previousStageId;
                        window.location.href = `{{ route('deals.view') }}?id=${dealId}&action=won`;
                        return;
                    }

                    select.disabled = true;

                    try {
                        const response = await 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"]').content,
                            },
                            body: JSON.stringify({ stage_id: selectedStageId }),
                        });
                        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.');
                        }

                        if (data.approval_status === 'pending') {
                            window.alert(data.message || 'Closure approval requested.');
                            window.location.reload();
                            return;
                        }

                        select.dataset.currentStage = String(data.stage_id || selectedStageId);
                        select.value = select.dataset.currentStage;
                        select.disabled = false;
                    } catch (error) {
                        select.value = previousStageId;
                        select.disabled = false;
                        window.alert(error.message);
                    }
                });
            });

            document.querySelectorAll('[data-id]').forEach(function(element) {
                element.addEventListener('click', function() {
                    const selectedId = this.getAttribute('data-id');
                    console.log(selectedId); // Log the selected ID for debugging

                    // Map selectedId to numeric value based on activityTypes
                    const activityType = Alpine.store('activity').activityTypes[selectedId];
                    Alpine.store('activity').selectedButton = activityType;

                    const dealId = this.getAttribute('data-deal-id');
                    console.log(dealId); // Log the lead ID for debugging

                    // Set the value of the hidden lead_id input field
                    const dealInput = document.querySelector('input[name="deal_id"]');
                    if (dealInput) {
                        dealInput.value = dealId;
                    }
                    // Open the modal using Bootstrap's JavaScript API
                    const modal = document.querySelector('#addActivity');

                });
            });

            // Event listener for modal close
            const modalElement = document.querySelector('#addActivity');
            modalElement.addEventListener('hidden.bs.modal', function() {
                // Remove the backdrop after modal is closed
                removeBackdrop();
            });
        });

        // Function to add the backdrop if it's not there
        function addBackdrop() {
            if (!document.querySelector('.modal-backdrop')) {
                const backdrop = document.createElement('div');
                backdrop.classList.add('modal-backdrop', 'fade', 'show');
                document.body.appendChild(backdrop);
            }
        }

        // Function to remove the backdrop if exists
        function removeBackdrop() {
            const existingBackdrop = document.querySelector('.modal-backdrop');
            if (existingBackdrop) {
                existingBackdrop.remove();
            }
        }
    </script>


@endsection
