@extends('layouts.app')

@section('title', 'My Activities')

@section('content')
    <style>
        .my-activities-page { --activity-border: #e7ebf2; --activity-muted: #667085; }
        .my-activities-page .activities-intro { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 22px 24px; margin-bottom: 20px; border: 1px solid var(--activity-border); border-radius: 16px; background: linear-gradient(135deg, #ffffff 0%, #f5f7ff 100%); }
        .my-activities-page .activities-intro-icon { display: inline-flex; width: 48px; height: 48px; flex: 0 0 auto; align-items: center; justify-content: center; border-radius: 14px; color: #fff; background: linear-gradient(135deg, #3454d1, #5674e8); font-size: 20px; box-shadow: 0 8px 18px rgba(52, 84, 209, .2); }
        .activity-quick-actions { padding: 5px; border: 1px solid #e7ebf2; border-radius: 12px; background: #fff; }
        .activity-quick-action { display: inline-flex; width: auto; min-width: 40px; align-items: center; gap: 7px; padding: 9px 11px; border: 0; border-radius: 9px; }
        .activity-quick-action span { font-size: 12px; font-weight: 650; }
        .professional-activity-modal .modal-content { overflow: hidden; border: 0; border-radius: 17px; box-shadow: 0 25px 70px rgba(16,24,40,.2); }
        .professional-activity-modal .modal-header { padding: 20px 24px; border-bottom: 1px solid #e8ecf2; background: linear-gradient(135deg,#f5f7ff,#fff); }
        .professional-activity-modal .call-modal-icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 11px; background: #3454d1; color: #fff; font-size: 18px; box-shadow: 0 7px 17px rgba(52,84,209,.22); }
        .professional-activity-modal .modal-body { padding: 22px 24px; background: #fff; }
        .professional-activity-modal .call-modal-section { margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid #edf0f4; }
        .professional-activity-modal .call-modal-section:last-child { margin-bottom: 0; padding-bottom: 0; border-bottom: 0; }
        .professional-activity-modal .call-modal-section-title { display: flex; align-items: center; gap: 8px; margin-bottom: 14px; color: #344054; font-size: 12px; font-weight: 800; text-transform: uppercase; letter-spacing: .04em; }
        .professional-activity-modal .form-label { margin-bottom: 6px; color: #344054; font-size: 12px; font-weight: 700; }
        .professional-activity-modal .form-control, .professional-activity-modal .form-select { min-height: 43px; border-color: #dce2eb; border-radius: 9px; }
        .professional-activity-modal .select2-container { width: 100% !important; }
        .professional-activity-modal .select2-container .select2-selection--multiple { min-height: 43px; padding: 4px 7px; border-color: #dce2eb; border-radius: 9px; }
        .professional-activity-modal .select2-selection__choice { border: 0; border-radius: 6px; background: #e9edff; color: #3454d1; font-weight: 650; }
        .professional-activity-modal .readonly-call-field { background: #f8fafc; color: #667085; }
        .professional-activity-modal .modal-footer { padding: 15px 24px; border-top: 1px solid #e8ecf2; background: #fbfcfe; }
        .activities-summary .activity-metric { position: relative; height: 100%; min-height: 122px; overflow: hidden; border: 1px solid var(--activity-border); border-radius: 14px; box-shadow: none; }
        .activities-summary .activity-metric::after { content: ''; position: absolute; right: -24px; bottom: -28px; width: 88px; height: 88px; border-radius: 50%; background: currentColor; opacity: .045; }
        .activities-summary .activity-metric .metric-label { color: var(--activity-muted); font-size: 12px; font-weight: 650; letter-spacing: .015em; }
        .activities-summary .activity-metric .metric-value { margin: 5px 0 0; color: #1d2939; font-size: 27px; font-weight: 750; line-height: 1; }
        .activities-summary .activity-metric .metric-caption { display: block; margin-top: 9px; color: #98a2b3; font-size: 11px; }
        .activities-summary .metric-icon { display: inline-flex; width: 42px; height: 42px; align-items: center; justify-content: center; border-radius: 12px; font-size: 17px; }
        .activities-board { overflow: visible; white-space: normal; }
        .activity-dashboard-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 20px; align-items: start; }
        .activities-board table { margin-bottom: 0; overflow: hidden; border: 1px solid var(--activity-border) !important; border-collapse: separate; border-spacing: 0; border-radius: 14px; background: #fff; box-shadow: 0 5px 20px rgba(15, 23, 42, .035); }
        .activities-board thead th { padding: 14px 15px !important; border: 0 !important; border-right: 1px solid rgba(255,255,255,.14) !important; background: linear-gradient(135deg, #263b8f, #3454d1) !important; color: #fff; vertical-align: middle; }
        .activities-board thead th:last-child { border-right: 0 !important; }
        .activities-board .stage-title { color: #fff !important; font-size: 13px !important; font-weight: 700; letter-spacing: .01em; }
        .activities-board .sortable-column { width: 50%; padding: 12px !important; border: 0 !important; border-right: 1px solid var(--activity-border) !important; white-space: normal; background: #f7f9fc !important; }
        .activities-board .sortable-column:last-child { border-right: 0 !important; }
        .activities-board .single-ticket-item { margin-bottom: 9px !important; padding: 13px 14px !important; border: 1px solid #e6eaf1; border-radius: 11px !important; background: #fff; box-shadow: none !important; transition: border-color .2s, transform .2s, box-shadow .2s; }
        .activities-board a:hover .single-ticket-item, .activities-board .single-ticket-item:hover { border-color: #bdc8f8; transform: translateY(-1px); box-shadow: 0 7px 17px rgba(52,84,209,.08) !important; }
        .activities-board .ticket-title { min-width: 0; color: #253047 !important; font-size: .88rem; font-weight: 700; }
        .activities-board .badge { border-radius: 7px; font-size: 10px; font-weight: 700; }
        .activities-empty, .activities-board .text-gray-500.text-center { min-height: 94px; display: grid; place-items: center; padding: 16px; color: #98a2b3 !important; font-size: 12px; text-align: center; }
        .activities-board > .activity-dashboard-grid > div > table + table { margin-top: 20px !important; }
        @media (max-width: 767.98px) {
            .my-activities-page .activities-intro { align-items: flex-start; padding: 18px; }
            .activity-dashboard-grid { grid-template-columns: 1fr; }
            .activity-quick-action span { display: none; }
            .activities-board table, .activities-board tbody, .activities-board tr, .activities-board td { display: block; width: 100% !important; }
            .activities-board thead { display: none; }
            .activities-board .sortable-column { min-height: 110px; border-right: 0 !important; border-bottom: 10px solid #fff !important; }
            .activities-board .sortable-column::before { content: attr(data-column-title); display: block; margin: -12px -12px 12px; padding: 11px 13px; background: linear-gradient(135deg, #263b8f, #3454d1); color: #fff; font-size: 12px; font-weight: 700; }
        }
    </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="m-b-10">My Activities</h5>
            </div>
            <ul class="breadcrumb">
                <li class="breadcrumb-item"><a href="{{ route('index') }}">Home</a></li>
                <li class="breadcrumb-item">My Activities</li>
            </ul>
        </div>
        <div class="page-header-right ms-auto">
            <div class="page-header-right-items">
                <div class="d-flex d-md-none">
                    <a href="javascript:void(0)" class="page-header-right-close-toggle">
                        <i class="feather-arrow-left me-2"></i>
                        <span>Back</span>
                    </a>
                </div>
                <div class="d-flex align-items-center gap-2 page-header-right-items-wrapper activity-quick-actions">

                    <button type="button" class="btn btn-icon btn-light-brand activity-quick-action" data-bs-toggle="modal"
                        data-bs-target="#addMeetingActivity" title="Meeting" aria-label="Add meeting">
                        <i class="feather-calendar"></i><span>Meeting</span>
                    </button>
                    <button type="button" class="btn btn-icon btn-light-brand activity-quick-action" data-bs-toggle="modal"
                        data-bs-target="#addCallActivity" title="Call" aria-label="Add call">
                        <i class="feather-phone"></i><span>Call</span>
                    </button>
                    <button type="button" class="btn btn-icon btn-light-brand activity-quick-action" data-bs-toggle="modal"
                        data-bs-target="#addTaskActivity" title="Task" aria-label="Add task">
                        <i class="feather-clipboard"></i><span>Task</span>
                    </button>
                    <button type="button" class="btn btn-icon btn-light-brand activity-quick-action" data-bs-toggle="modal"
                        data-bs-target="#addEmailActivity" title="Email" aria-label="Add email">
                        <i class="feather-mail"></i><span>Email</span>
                    </button>
                    @canany(['create_leads', 'create_deals', 'create_tickets'])
                    <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-list"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-end">
                            @can('create_leads')
                            <a href="{{ route('leads-create') }}" class="dropdown-item">
                                <i class="feather-check-circle me-3"></i>
                                <span>Create Lead</span>
                            </a>
                            @endcan
                            @can('create_deals')
                            <a href="{{ route('deals-create') }}" class="dropdown-item">
                                <i class="feather-file me-3"></i>
                                <span>Create Deal</span>
                            </a>
                            @endcan
                            @can('create_tickets')
                            <a href="{{ route('ticket-create') }}" class="dropdown-item">
                                <i class="feather-tag me-3"></i>
                                <span>Create Ticket</span>
                            </a>
                            @endcan
                        </div>
                    </div>
                    @endcanany
                    <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>

                </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">Total Customers</span>
                                        <span class="fs-24 fw-bolder d-block">26,595</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">Active Customers</span>
                                        <span class="fs-24 fw-bolder d-block">2,245</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">New Customers</span>
                                        <span class="fs-24 fw-bolder d-block">1,254</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">Inactive Customers</span>
                                        <span class="fs-24 fw-bolder d-block">4,586</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 my-activities-page">
        <div class="activities-intro">
            <div class="d-flex align-items-center gap-3">
                <span class="activities-intro-icon"><i class="feather-activity"></i></span>
                <div>
                    <span class="text-uppercase text-primary fw-bold" style="font-size: 10px; letter-spacing: .08em;">Personal workspace</span>
                    <h4 class="fw-bold mb-1 mt-1">Activity Command Center</h4>
                    <p class="text-muted mb-0">Plan today's work, monitor assigned records, and keep every follow-up moving.</p>
                </div>
            </div>
            <div class="text-end d-none d-md-block">
                <div class="fw-semibold text-dark">{{ now()->format('l, d M Y') }}</div>
                <small class="text-muted">{{ $todayactivities->count() }} activities scheduled today</small>
            </div>
        </div>
        <div class="row activities-summary g-3 mb-3">
            <div class="col-xxl-3 col-md-6">
                <div class="card card-body activity-metric text-primary">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="me-3">
                            <span class="metric-label">Upcoming Calls</span>
                            <h5 class="metric-value">{{ $callCount }}</h5>
                            <span class="metric-caption">Scheduled from today onward</span>
                        </div>
                        <div class="metric-icon bg-soft-primary text-primary">
                            <i class="feather-phone-call"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xxl-3 col-md-6">
                <div class="card card-body activity-metric text-success">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="me-3">
                            <span class="metric-label">New Leads</span>
                            <h5 class="metric-value">{{ $monthLeadsCount }}</h5>
                            <span class="metric-caption">Assigned during this month</span>
                        </div>
                        <div class="metric-icon bg-soft-success text-success">
                            <i class="feather-user-plus"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xxl-3 col-md-6">
                <div class="card card-body activity-metric text-warning">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="me-3">
                            <span class="metric-label">Open Deals</span>
                            <h5 class="metric-value">{{ $monthOpenDeals }}</h5>
                            <span class="metric-caption">Active opportunities this month</span>
                        </div>
                        <div class="metric-icon bg-soft-warning text-warning">
                            <i class="feather-briefcase"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xxl-3 col-md-6">
                <div class="card card-body activity-metric text-info">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="me-3">
                            <span class="metric-label">Closed Deals</span>
                            <h5 class="metric-value">{{ $monthClosedDealsCount }}</h5>
                            <span class="metric-caption">Completed during this month</span>
                        </div>
                        <div class="metric-icon bg-soft-info text-info">
                            <i class="feather-check-circle"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>



        <div class="activities-board">
            <!-- Wrapper Div for Tables -->
            <div class="activity-dashboard-grid">

                <!-- First Table -->
                <table class="table border-collapse border border-gray-300 rounded-lg overflow-hidden w-1/2"
                    style="table-layout: fixed; width: 100%;">
                    <thead>
                        <tr style="background-color: #007bffcb; color: white;">
                            <th class="text-center" style="width: 230px; padding: 10px; border-left: 1px solid #ddd;">
                                <h5 class="stage-title text-truncate mb-0"
                                    style="margin: 0; font-size: 16px; color: white;">Today's Activities
                                </h5>
                            </th>
                            <th class="text-center" style="padding: 8px; border-left: 1px solid #ddd;">
                                <h5 class="stage-title text-truncate mb-0"
                                    style="margin: 0; font-size: 16px; color: white;">Assigned to Me — Status</h5>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="sortable-column align-top p-2 border border-white bg-gray-100" data-column-title="Today's Activities">
                                @forelse ($todayactivities as $activity)
                                    <div class="card card-body mb-1 single-ticket-item p-3 bg-white shadow-sm rounded-lg hover:shadow-md transition-transform"
                                        style="width: 100%; height: auto;">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h5 class="ticket-title text-truncate text-gray-900 font-semibold mb-1">
                                                {{ $activity->title ?? 'No Title' }}

                                            </h5>
                                            <span class="badge bg-success text-white text-sm ms-2">
                                                {{ $activityTypes[$activity->activity_type_id] ?? 'Unknown Type' }}
                                            </span>
                                        </div>

                                        {{-- <span class="fs-11 text-gray-600 text-sm">
                                            @php
                                                $displayDate =
                                                    $activity->start_date ??
                                                    ($activity->due_date ??
                                                        ($activity->received_on ?? $activity->created_at));
                                            @endphp
                                            {{ \Carbon\Carbon::parse($displayDate)->format('d M Y') }}
                                        </span> --}}
                                        <div class="d-flex justify-content-between">
                                            <span class="fs-11 text-gray-600 text-sm">
                                                {{ \Carbon\Carbon::parse($activity->created_at)->format('d M Y') }}
                                            </span>
                                            <span class="fs-11 text-gray-600 text-sm">
                                                {{ \Carbon\Carbon::parse($activity->created_at)->diffForHumans() }}
                                            </span>
                                        </div>
                                        <span class="text-gray-700 text-sm text-truncate-3-line">
                                            {{ optional(\App\Models\Contact::find($activity->contact_id))->first_name ?? '' }}
                                            {{ optional(\App\Models\Contact::find($activity->contact_id))->last_name ?? '' }}
                                        </span>
                                    </div>
                                @empty
                                    <div class="text-gray-500 text-center">No Activities Today</div>
                                @endforelse
                            </td>
                            <td class="sortable-column align-top p-2 border border-white bg-gray-100" data-column-title="Assigned to Me — Status">
                                @forelse ($allItems as $item)
                                    @php
                                        // Determine item type (Lead, Deal, Ticket)
                                        $itemType = get_class($item); // Check the class name for type
                                        $priorityClass = '';
                                        $priorityLabel = '';
                                        $itemUrl = match ($itemType) {
                                            'App\\Models\\Lead' => route('leads.view', ['id' => $item->id]),
                                            'App\\Models\\Deal' => route('deals.view', ['id' => $item->id]),
                                            'App\\Models\\Ticket' => route('ticket.view', ['id' => $item->id]),
                                            default => '#',
                                        };

                                        // Priority logic
                                        if (isset($item->priority_id)) {
                                            switch ($item->priority_id) {
                                                case 1: // High
                                                    $priorityLabel = 'High';
                                                    $priorityClass = 'badge bg-soft-success text-success';
                                                    break;
                                                case 2: // Medium
                                                    $priorityLabel = 'Medium';
                                                    $priorityClass = 'badge bg-soft-warning text-warning';
                                                    break;
                                                case 3: // Low
                                                    $priorityLabel = 'Low';
                                                    $priorityClass = 'badge bg-soft-danger text-danger';
                                                    break;
                                                default:
                                                    $priorityLabel = 'No Priority';
                                                    $priorityClass = 'badge bg-soft-secondary text-secondary';
                                                    break;
                                            }
                                        }
                                    @endphp

                                    <!-- Card for each item (Lead, Deal, Ticket) -->
                                    <a href="{{ $itemUrl }}" class="text-decoration-none">
                                        <div class="card card-body mb-1 single-ticket-item p-3 bg-white shadow-sm rounded-lg hover:shadow-md transition-transform"
                                            style="width: 100%; height: auto;">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <h5 class="ticket-title text-truncate text-gray-900 font-semibold mb-1">
                                                    @if ($itemType === 'App\Models\Lead')
                                                        {{ $item->topic ?? 'No Title' }}
                                                    @elseif ($itemType === 'App\Models\Deal')
                                                        {{ $item->name ?? 'No Title' }}
                                                    @elseif ($itemType === 'App\Models\Ticket')
                                                        {{ $item->topic ?? 'No Title' }}
                                                    @else
                                                        No Title
                                                    @endif
                                                </h5>
                                                <span
                                                    class="badge
                                                @if ($itemType === 'App\Models\Lead') bg-primary
                                                @elseif ($itemType === 'App\Models\Deal') bg-warning
                                                @elseif ($itemType === 'App\Models\Ticket') bg-success
                                                @else bg-secondary @endif
                                                text-white text-sm ms-2">
                                                    @if ($itemType === 'App\Models\Lead')
                                                        Lead
                                                    @elseif ($itemType === 'App\Models\Deal')
                                                        Deal
                                                    @elseif ($itemType === 'App\Models\Ticket')
                                                        Ticket
                                                    @else
                                                        Unknown Type
                                                    @endif
                                                </span>
                                            </div>

                                            <div class="mt-2">
                                                @if ($itemType === 'App\Models\Lead')
                                                    <span class="badge bg-soft-primary text-primary">
                                                        {{ \App\Models\LeadStage::find($item->stage_id)?->name ?? 'No Lead Status' }}
                                                    </span>
                                                @elseif ($itemType === 'App\Models\Deal')
                                                    <span class="badge bg-soft-warning text-warning">
                                                        {{ \App\Models\DealStage::find($item->stage_id)?->name ?? 'No Deal Status' }}
                                                    </span>
                                                @elseif ($itemType === 'App\Models\Ticket')
                                                    <span class="badge bg-soft-success text-success">
                                                        {{ \App\Models\TicketStage::find($item->stage_id)?->name ?? 'No Ticket Status' }}
                                                    </span>
                                                @endif
                                            </div>
                                        </div>
                                    </a>

                                @empty
                                    <div class="text-gray-500 text-center">No Tickets, Leads, or Deals assigned to you.</div>
                                @endforelse
                            </td>



                        </tr>
                    </tbody>
                </table>

                <!-- Second Table Container (with Third Table Below it) -->
                <div style="width: 100%; padding-left: 0.05px; padding-right: 0.5px;">

                    <!-- Second Table -->
                    <table class="table border-collapse border border-gray-300 rounded-lg overflow-hidden w-full"
                        style="table-layout: fixed;">
                        <thead>
                            <tr style="background-color: #007bffcb; color: white;">
                                <th class="text-center" style="padding: 8px; border-left: 1px solid #ddd;">
                                    <h5 class="stage-title text-truncate mb-0"
                                        style="margin: 0; font-size: 16px; color: white;">Today's Meetings
                                    </h5>
                                </th>
                                <th class="text-center" style="padding: 8px; border-left: 1px solid #ddd;">
                                    <h5 class="stage-title text-truncate mb-0"
                                        style="margin: 0; font-size: 16px; color: white;">Reminders</h5>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="sortable-column align-top p-2 border border-white bg-gray-100" data-column-title="Today's Meetings">
                                    @forelse ($todayMeetings as $meeting)
                                        <div class="card card-body mb-1 single-ticket-item p-3 bg-white shadow-sm rounded-lg hover:shadow-md transition-transform"
                                            style="width: 100%; height: auto;">
                                            <h5 class="ticket-title text-truncate text-gray-900 font-semibold mb-1">
                                                {{ $meeting->title ?? 'No Title' }}
                                            </h5>
                                            <div class="d-flex justify-content-between">
                                                <span class="fs-11 text-gray-600 text-sm">
                                                    @php
                                                        $displayDate = $meeting->start_date ?? $meeting->created_at;
                                                    @endphp
                                                    {{ \Carbon\Carbon::parse($displayDate)->format('d M Y') }}
                                                </span>
                                                <span class="fs-11 text-gray-600 text-sm">
                                                    {{ \Carbon\Carbon::parse($meeting->created_at)->diffForHumans() }}
                                                </span>
                                            </div>


                                            <span class="text-gray-700 text-sm text-truncate-3-line">
                                                {{ optional(\App\Models\Contact::find($meeting->contact_id))->first_name ?? '' }}
                                                {{ optional(\App\Models\Contact::find($meeting->contact_id))->last_name ?? '' }}
                                            </span>
                                        </div>
                                    @empty
                                        <div class="text-gray-500 text-center">No Meetings Today</div>
                                    @endforelse
                                </td>

                                <td class="sortable-column align-top p-2 border border-white bg-gray-100" data-column-title="Reminders">
                                    <div class="activities-empty"><span><i class="feather-bell-off d-block fs-4 mb-2"></i>No reminders due</span></div>
                                </td>
                            </tr>
                        </tbody>
                    </table>

                    <!-- Third Table Below the Second Table -->
                    <table class="table border-collapse border border-gray-300 rounded-lg overflow-hidden w-full"
                        style="table-layout: fixed; margin-top: 20px;">
                        <thead>
                            <tr style="background-color: #007bffcb; color: white;">
                                <th class="text-center" style="padding: 8px; border-left: 1px solid #ddd;">
                                    <h5 class="stage-title text-truncate mb-0"
                                        style="cursor: grab; margin: 0; font-size: 16px; color: white;">Recent Contacts
                                    </h5>
                                </th>
                                <th class="text-center" style="padding: 8px; border-left: 1px solid #ddd;">
                                    <h5 class="stage-title text-truncate mb-0"
                                        style="cursor: grab; margin: 0; font-size: 16px; color: white;">Closed Deals This Month</h5>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="sortable-column align-top p-2 border border-white bg-gray-100" data-column-title="Recent Contacts">
                                    @forelse ($recentContacts as $contact)
                                        <div class="card card-body mb-1 single-ticket-item p-3 bg-white shadow-sm rounded-lg hover:shadow-md transition-transform"
                                            style="width: 100%; height: auto;">
                                            <!-- Contact Name -->
                                            <h5 class="ticket-title text-truncate text-gray-900 font-semibold mb-1">
                                                {{ $contact->first_name ?? 'No Name' }}
                                                {{ $contact->last_name ?? 'No Name' }}
                                            </h5>

                                            <!-- Created Date -->
                                            <div class="d-flex justify-content-between">
                                                <span class="fs-11 text-gray-600 text-sm">
                                                    {{ \Carbon\Carbon::parse($contact->created_at)->format('d M Y') }}
                                                </span>
                                                <span class="fs-11 text-gray-600 text-sm">
                                                    {{ \Carbon\Carbon::parse($contact->created_at)->diffForHumans() }}
                                                </span>
                                            </div>

                                        </div>
                                    @empty
                                        <div class="text-gray-500 text-center">No Recent Contacts</div>
                                    @endforelse
                                </td>
                                <td class="sortable-column align-top p-2 border border-white bg-gray-100" data-column-title="Closed Deals This Month">
                                    @forelse ($monthClosedDeals as $deal)
                                        <a href="{{ route('deals.view', ['id' => $deal->id]) }}"
                                            class="text-decoration-none">
                                            <div class="card card-body mb-1 single-ticket-item p-3 bg-white shadow-sm rounded-lg hover:shadow-md transition-transform"
                                                style="width: 100%; height: auto;">
                                                <h5 class="ticket-title text-truncate text-gray-900 font-semibold mb-1">
                                                    {{ $deal->name ?? 'No Name' }}
                                                </h5>
                                                <div class="d-flex justify-content-between">
                                                    <span class="fs-11 text-gray-600 text-sm">
                                                        {{ \Carbon\Carbon::parse($deal->updated_at)->format('d M Y') }}
                                                    </span>
                                                    <span class="fs-11 text-gray-600 text-sm">
                                                        {{ \Carbon\Carbon::parse($deal->updated_at)->diffForHumans() }}
                                                    </span>
                                                </div>
                                            </div>
                                        </a>
                                    @empty
                                        <div class="text-gray-500 text-center">No Closed Deals This Month</div>
                                    @endforelse
                                </td>

                            </tr>
                        </tbody>
                    </table>

                </div>

            </div>

        </div>







    </div>
@endsection

@section('modals')
    @php
        $myCallContactById = $contacts->keyBy('id');
        $myCallAllowedOwnerIds = $users->pluck('id')->map(fn ($id) => (int) $id);
        $myCallRecords = collect();
        $addMyCallRecord = function ($type, $record, $label, $contact, $owner, $phone = null) use ($myCallRecords, $myCallAllowedOwnerIds) {
            $ownerId = $owner?->id && $myCallAllowedOwnerIds->contains((int) $owner->id) ? (int) $owner->id : (int) auth()->id();
            $myCallRecords->push([
                'type' => $type, 'id' => (int) $record->id, 'label' => $label,
                'contact_id' => $contact?->id ? (int) $contact->id : null,
                'contact_name' => $contact ? (trim($contact->first_name.' '.$contact->last_name) ?: 'Contact #'.$contact->id) : 'No linked contact',
                'owner_id' => $ownerId, 'owner_name' => $owner?->name ?: auth()->user()->name,
                'phone' => $phone ?: $contact?->contactPhones?->first()?->phone,
            ]);
        };
        foreach ($leads as $lead) {
            $contact = $myCallContactById->get($lead->primary_contact_id);
            $addMyCallRecord('lead', $lead, trim($lead->first_name.' '.$lead->last_name) ?: ($lead->topic ?: 'Lead #'.$lead->id), $contact, $lead->assignedUser, $lead->contactPhones->first()?->phone);
        }
        foreach ($contacts as $contact) $addMyCallRecord('contact', $contact, trim($contact->first_name.' '.$contact->last_name) ?: 'Contact #'.$contact->id, $contact, $contact->assignedUser, $contact->contactPhones->first()?->phone);
        foreach ($accounts as $account) $addMyCallRecord('account', $account, $account->account_name ?: 'Account #'.$account->id, $account->primaryContact, $account->assignedUser, $account->contactPhones->first()?->phone);
        foreach ($deals as $deal) $addMyCallRecord('deal', $deal, $deal->name ?: 'Deal #'.$deal->id, $deal->contact, $deal->assignedUser, $deal->contactPhones->first()?->phone);
        foreach ($projects as $project) $addMyCallRecord('project', $project, $project->name ?: 'Project #'.$project->id, $project->account?->primaryContact, $project->owner);
        foreach ($cases as $case) {
            $contact = $case->contact ?: $case->deal?->contact ?: $case->account?->primaryContact ?: $myCallContactById->get($case->lead?->primary_contact_id);
            $addMyCallRecord('case', $case, trim(($case->case_number ?: 'Case #'.$case->id).' — '.$case->subject), $contact, $case->assignee, $contact?->contactPhones?->first()?->phone ?: $case->lead?->contactPhones?->first()?->phone);
        }
        $myEmailRecipientOptions = collect();
        foreach ($contacts as $contact) foreach ($contact->contactEmails as $email) $myEmailRecipientOptions->push(['email'=>$email->email,'label'=>(trim($contact->first_name.' '.$contact->last_name) ?: 'Contact #'.$contact->id).' — '.$email->email]);
        foreach ($leads as $lead) foreach ($lead->contactEmails as $email) $myEmailRecipientOptions->push(['email'=>$email->email,'label'=>(trim($lead->first_name.' '.$lead->last_name) ?: 'Lead #'.$lead->id).' — '.$email->email]);
        foreach ($accounts as $account) foreach ($account->contactEmails as $email) $myEmailRecipientOptions->push(['email'=>$email->email,'label'=>($account->account_name ?: 'Account #'.$account->id).' — '.$email->email]);
        foreach ($deals as $deal) foreach (($deal->contact?->contactEmails ?: collect()) as $email) $myEmailRecipientOptions->push(['email'=>$email->email,'label'=>($deal->name ?: 'Deal #'.$deal->id).' — '.$email->email]);
        $myEmailRecipientOptions = $myEmailRecipientOptions->filter(fn($item)=>filter_var($item['email'], FILTER_VALIDATE_EMAIL))->unique('email')->values();
    @endphp

    <div class="modal fade professional-activity-modal" id="addCallActivity" tabindex="-1" aria-labelledby="addCallActivityLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <form class="modal-content" id="myCallActivityForm" method="POST" action="{{ route('activities.store') }}" enctype="multipart/form-data">
                @csrf
                <input type="hidden" name="submission_token" value="{{ $submissionToken }}">
                <input type="hidden" name="return_to" value="myactivities">
                <input type="hidden" name="popup_type" value="call">
                <input type="hidden" name="activity_type_id" value="1">
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-3">
                        <span class="call-modal-icon"><i class="feather-phone-call"></i></span>
                        <div><h5 class="modal-title fw-bold mb-1" id="addCallActivityLabel">Create Call Activity</h5><p class="text-muted fs-12 mb-0">Schedule a call and connect it to the appropriate CRM record.</p></div>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    @if ($errors->any() && old('popup_type') === 'call')
                        <div class="alert alert-danger"><strong>The Call could not be created.</strong><ul class="mb-0 mt-2">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>
                    @endif
                    <section class="call-modal-section">
                        <div class="call-modal-section-title"><i class="feather-edit-3 text-primary"></i>Call Details</div>
                        <div class="row g-3">
                            <div class="col-12"><label class="form-label" for="myCallSubject">Call Subject <span class="text-danger">*</span></label><input class="form-control" id="myCallSubject" name="title" maxlength="255" required placeholder="Enter call subject"></div>
                            <div class="col-md-5"><label class="form-label" for="myCallRelatedType">Related To <span class="text-danger">*</span></label><select class="form-select" id="myCallRelatedType" required><option value="">Select module</option><option value="lead">Lead</option><option value="contact">Contact</option><option value="account">Account</option><option value="deal">Deal</option><option value="case">Case</option></select></div>
                            <div class="col-md-7"><label class="form-label" for="myCallRelatedRecord">Related Record <span class="text-danger">*</span></label><select class="form-select" id="myCallRelatedRecord" required disabled><option value="">Select record</option></select><div id="myCallRelatedInputs"></div></div>
                            <div class="col-md-6"><label class="form-label">Contact Owner</label><input class="form-control readonly-call-field" id="myCallOwnerName" readonly placeholder="Retrieved from related record"><input type="hidden" name="owner" id="myCallOwnerId" value="{{ auth()->id() }}"></div>
                            <div class="col-md-6"><label class="form-label">Contact Person</label><input class="form-control readonly-call-field" id="myCallContactPerson" readonly placeholder="Retrieved from related record"><input type="hidden" name="callFrom" id="myCallFrom"></div>
                            <div class="col-md-6"><label class="form-label" for="myCallPhone">Phone Number From <span class="text-danger">*</span></label><input class="form-control" id="myCallPhone" name="phoneNumber" required placeholder="Phone number"></div>
                            <div class="col-md-6"><label class="form-label" for="myCallDirection">Call Type <span class="text-danger">*</span></label><select class="form-select" id="myCallDirection" name="direction" required><option value="">Select call type</option><option value="inbound">Incoming</option><option value="outbound">Outgoing</option></select></div>
                        </div>
                    </section>
                    <section class="call-modal-section">
                        <div class="call-modal-section-title"><i class="feather-users text-primary"></i>Assignment &amp; Schedule</div>
                        <div class="row g-3">
                            <div class="col-12"><label class="form-label" for="myCallAssignees">Assigned To <span class="text-danger">*</span></label><select class="form-select" id="myCallAssignees" name="assignee_ids[]" multiple required data-placeholder="Select one or more users">@foreach($users as $user)<option value="{{ $user->id }}" @selected($user->id === auth()->id())>{{ $user->name }}</option>@endforeach</select></div>
                            <div class="col-md-6"><label class="form-label" for="myCallDateTime">Call Date &amp; Time <span class="text-danger">*</span></label><input class="form-control" id="myCallDateTime" type="datetime-local" value="{{ now()->format('Y-m-d\TH:i') }}" required><input type="hidden" name="start_date" id="myCallStartDate"><input type="hidden" name="start_time" id="myCallStartTime"><input type="hidden" name="end_date" id="myCallEndDate"><input type="hidden" name="end_time" id="myCallEndTime"></div>
                            <div class="col-md-6"><label class="form-label" for="myCallReminder">Reminder</label><input class="form-control" id="myCallReminder" type="datetime-local" name="remind_at"></div>
                            <div class="col-md-6"><label class="form-label" for="myCallEscalation">Escalation After</label><select class="form-select" id="myCallEscalation" name="reminder_escalation_hours"><option value="4">4 hours</option><option value="12">12 hours</option><option value="24" selected>24 hours</option><option value="48">48 hours</option><option value="72">72 hours</option></select></div>
                            <div class="col-md-6"><label class="form-label" for="myCallDuration">Duration <span class="text-danger">*</span></label><input class="form-control" id="myCallDuration" name="duration" required placeholder="e.g. 15 minutes"></div>
                            <div class="col-md-6"><label class="form-label" for="myCallStatus">Status <span class="text-danger">*</span></label><select class="form-select" id="myCallStatus" name="lifecycle_status" required><option value="planned">Planned</option><option value="open">Open</option><option value="in_progress">In Progress</option><option value="completed">Completed</option><option value="cancelled">Cancelled</option></select></div>
                            <div class="col-md-6"><label class="form-label" for="myCallOutcome">Outcome <span class="text-danger">*</span></label><select class="form-select" id="myCallOutcome" name="outcome" required><option value="">Select outcome</option><option value="interested">Interested</option><option value="follow_up_required">Follow-up Required</option><option value="not_interested">Not Interested</option></select></div>
                        </div>
                    </section>
                    <section class="call-modal-section">
                        <div class="call-modal-section-title"><i class="feather-file-text text-primary"></i>Notes &amp; Evidence</div>
                        <div class="row g-3">
                            <div class="col-12"><label class="form-label" for="myCallNotes">Note</label><textarea class="form-control" id="myCallNotes" name="description" rows="4" placeholder="Add call notes"></textarea></div>
                            <div class="col-12"><label class="form-label" for="myCallEvidence">Evidence Attachment</label><input class="form-control" id="myCallEvidence" type="file" name="attachment" accept="image/*,audio/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"><small class="text-muted">Attach supporting evidence up to 10 MB.</small></div>
                        </div>
                    </section>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary"><i class="feather-phone-call me-2"></i>Create Call</button></div>
            </form>
        </div>
    </div>

    <div class="modal fade professional-activity-modal" id="addMeetingActivity" tabindex="-1" aria-labelledby="addMeetingActivityLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <form class="modal-content" id="myMeetingActivityForm" method="POST" action="{{ route('activities.store') }}" enctype="multipart/form-data">
                @csrf
                <input type="hidden" name="submission_token" value="{{ $submissionToken }}">
                <input type="hidden" name="return_to" value="myactivities">
                <input type="hidden" name="popup_type" value="meeting">
                <input type="hidden" name="activity_type_id" value="2">
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-3"><span class="call-modal-icon"><i class="feather-calendar"></i></span><div><h5 class="modal-title fw-bold mb-1" id="addMeetingActivityLabel">Create Meeting Activity</h5><p class="text-muted fs-12 mb-0">Schedule a meeting, invite employees, and connect a CRM record.</p></div></div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    @if ($errors->any() && old('popup_type') === 'meeting')
                        <div class="alert alert-danger"><strong>The Meeting could not be created.</strong><ul class="mb-0 mt-2">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>
                    @endif
                    <section class="call-modal-section">
                        <div class="call-modal-section-title"><i class="feather-edit-3 text-primary"></i>Meeting Details</div>
                        <div class="row g-3">
                            <div class="col-12"><label class="form-label" for="myMeetingSubject">Meeting Subject <span class="text-danger">*</span></label><input class="form-control" id="myMeetingSubject" name="title" maxlength="255" required placeholder="Enter meeting subject"></div>
                            <div class="col-md-5"><label class="form-label" for="myMeetingRelatedType">Related To <span class="text-danger">*</span></label><select class="form-select" id="myMeetingRelatedType" required><option value="">Select module</option><option value="lead">Lead</option><option value="contact">Contact</option><option value="account">Account</option><option value="deal">Deal</option><option value="project">Project</option><option value="case">Case</option></select></div>
                            <div class="col-md-7"><label class="form-label" for="myMeetingRelatedRecord">Related Record <span class="text-danger">*</span></label><select class="form-select" id="myMeetingRelatedRecord" required disabled><option value="">Select record</option></select><div id="myMeetingRelatedInputs"></div></div>
                            <div class="col-md-6"><label class="form-label" for="myMeetingOwner">Owner To <span class="text-danger">*</span></label><select class="form-select" id="myMeetingOwner" name="owner" required>@foreach($users as $user)<option value="{{ $user->id }}" @selected($user->id===auth()->id())>{{ $user->name }}</option>@endforeach</select></div>
                            <div class="col-md-6"><label class="form-label" for="myMeetingAttendees">Attendees <span class="text-danger">*</span></label><select class="form-select" id="myMeetingAttendees" name="attendee_ids[]" multiple required data-placeholder="Select one or more employees">@foreach($users as $user)<option value="{{ $user->id }}" @selected($user->id===auth()->id())>{{ $user->name }}</option>@endforeach</select></div>
                        </div>
                    </section>
                    <section class="call-modal-section">
                        <div class="call-modal-section-title"><i class="feather-clock text-primary"></i>Schedule</div>
                        <div class="row g-3">
                            <div class="col-md-6"><label class="form-label" for="myMeetingDateTime">Date &amp; Time <span class="text-danger">*</span></label><input class="form-control" id="myMeetingDateTime" type="datetime-local" value="{{ now()->format('Y-m-d\TH:i') }}" required><input type="hidden" name="start_date" id="myMeetingStartDate"><input type="hidden" name="start_time" id="myMeetingStartTime"><input type="hidden" name="end_date" id="myMeetingEndDate"><input type="hidden" name="end_time" id="myMeetingEndTime"></div>
                            <div class="col-md-6"><label class="form-label" for="myMeetingDuration">Duration <span class="text-danger">*</span></label><select class="form-select" id="myMeetingDuration" name="duration" required><option value="15">15 minutes</option><option value="30" selected>30 minutes</option><option value="45">45 minutes</option><option value="60">1 hour</option><option value="90">1.5 hours</option><option value="120">2 hours</option></select></div>
                            <div class="col-md-6"><label class="form-label" for="myMeetingLocation">Location <span class="text-danger">*</span></label><select class="form-select" id="myMeetingLocation" name="meeting_location_type" required><option value="">Select location</option><option value="office">Office</option><option value="online">Online</option><option value="customer_location">Customer Location</option></select><input type="hidden" name="location" id="myMeetingLocationLabel"></div>
                            <div class="col-md-6"><label class="form-label" for="myMeetingType">Meeting Type <span class="text-danger">*</span></label><select class="form-select" id="myMeetingType" name="meeting_type" required><option value="">Select meeting type</option><option value="online">Online Platform</option><option value="physical">Physical</option><option value="phone">Phone</option></select></div>
                            <div class="col-md-6"><label class="form-label" for="myMeetingStatus">Status <span class="text-danger">*</span></label><select class="form-select" id="myMeetingStatus" name="lifecycle_status" required><option value="planned">Planned</option><option value="completed">Completed</option><option value="cancelled">Cancelled</option></select></div>
                            <div class="col-md-6"><label class="form-label" for="myMeetingReminder">Reminder Date</label><input class="form-control" id="myMeetingReminder" type="datetime-local" name="remind_at"></div>
                        </div>
                    </section>
                    <section class="call-modal-section">
                        <div class="call-modal-section-title"><i class="feather-file-text text-primary"></i>Agenda, Notes &amp; Evidence</div>
                        <div class="row g-3"><div class="col-12"><label class="form-label" for="myMeetingAgenda">Agenda <span class="text-danger">*</span></label><textarea class="form-control" id="myMeetingAgenda" name="agenda" rows="3" required placeholder="Add meeting agenda"></textarea></div><div class="col-12"><label class="form-label" for="myMeetingNote">Note</label><textarea class="form-control" id="myMeetingNote" name="description" rows="3" placeholder="Add meeting notes"></textarea></div><div class="col-12"><label class="form-label" for="myMeetingEvidence">Evidence Attachment</label><input class="form-control" id="myMeetingEvidence" type="file" name="attachment" accept="image/*,audio/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"><small class="text-muted">Attach supporting evidence up to 10 MB.</small></div></div>
                    </section>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary"><i class="feather-calendar me-2"></i>Create Meeting</button></div>
            </form>
        </div>
    </div>

    <div class="modal fade professional-activity-modal" id="addTaskActivity" tabindex="-1" aria-labelledby="addTaskActivityLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <form class="modal-content" id="myTaskActivityForm" method="POST" action="{{ route('activities.store') }}">
                @csrf
                <input type="hidden" name="submission_token" value="{{ $submissionToken }}">
                <input type="hidden" name="return_to" value="myactivities">
                <input type="hidden" name="popup_type" value="task">
                <input type="hidden" name="activity_type_id" value="3">
                <input type="hidden" name="start_time" value="09:00">
                <input type="hidden" name="end_time" value="17:00">
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-3"><span class="call-modal-icon"><i class="feather-check-square"></i></span><div><h5 class="modal-title fw-bold mb-1" id="addTaskActivityLabel">Create Task Activity</h5><p class="text-muted fs-12 mb-0">Create, assign, prioritize, and track a CRM task.</p></div></div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    @if ($errors->any() && old('popup_type') === 'task')
                        <div class="alert alert-danger"><strong>The Task could not be created.</strong><ul class="mb-0 mt-2">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>
                    @endif
                    <section class="call-modal-section">
                        <div class="call-modal-section-title"><i class="feather-edit-3 text-primary"></i>Task Details</div>
                        <div class="row g-3">
                            <div class="col-12"><label class="form-label" for="myTaskSubject">Task Subject <span class="text-danger">*</span></label><input class="form-control" id="myTaskSubject" name="title" maxlength="255" required placeholder="Enter task subject"></div>
                            <div class="col-12"><label class="form-label" for="myTaskDescription">Description</label><textarea class="form-control" id="myTaskDescription" name="description" rows="3" placeholder="Describe the task"></textarea></div>
                            <div class="col-md-5"><label class="form-label" for="myTaskRelatedType">Related To <span class="text-danger">*</span></label><select class="form-select" id="myTaskRelatedType" required><option value="">Select module</option><option value="lead">Lead</option><option value="contact">Contact</option><option value="account">Account</option><option value="deal">Deal</option><option value="project">Project</option><option value="case">Case</option></select></div>
                            <div class="col-md-7"><label class="form-label" for="myTaskRelatedRecord">Related Record <span class="text-danger">*</span></label><select class="form-select" id="myTaskRelatedRecord" required disabled><option value="">Select record</option></select><div id="myTaskRelatedInputs"></div></div>
                        </div>
                    </section>
                    <section class="call-modal-section">
                        <div class="call-modal-section-title"><i class="feather-users text-primary"></i>Ownership &amp; Schedule</div>
                        <div class="row g-3">
                            <div class="col-md-6"><label class="form-label" for="myTaskOwner">Owner <span class="text-danger">*</span></label><select class="form-select" id="myTaskOwner" name="owner" required>@foreach($users as $user)<option value="{{ $user->id }}" @selected($user->id===auth()->id())>{{ $user->name }}</option>@endforeach</select></div>
                            <div class="col-md-6"><label class="form-label" for="myTaskAssignees">Assigned To <span class="text-danger">*</span></label><select class="form-select" id="myTaskAssignees" name="assignee_ids[]" multiple required data-placeholder="Select one or more users">@foreach($users as $user)<option value="{{ $user->id }}" @selected($user->id===auth()->id())>{{ $user->name }}</option>@endforeach</select></div>
                            <div class="col-md-4"><label class="form-label" for="myTaskPriority">Priority <span class="text-danger">*</span></label><select class="form-select" id="myTaskPriority" name="priority" required><option value="">Select priority</option>@foreach($priorities as $priority)<option value="{{ $priority->id }}">{{ $priority->name }}</option>@endforeach</select></div>
                            <div class="col-md-4"><label class="form-label" for="myTaskStartDate">Start Date</label><input class="form-control" id="myTaskStartDate" type="date" name="start_date" value="{{ now()->toDateString() }}"></div>
                            <div class="col-md-4"><label class="form-label" for="myTaskDueDate">Due Date <span class="text-danger">*</span></label><input class="form-control" id="myTaskDueDate" type="date" name="due_date" value="{{ now()->addDay()->toDateString() }}" min="{{ now()->toDateString() }}" required><input type="hidden" name="end_date" id="myTaskEndDate" value="{{ now()->addDay()->toDateString() }}"></div>
                            <div class="col-md-6"><label class="form-label" for="myTaskStatus">Status <span class="text-danger">*</span></label><select class="form-select" id="myTaskStatus" name="lifecycle_status" required><option value="open">Open</option><option value="in_progress">In Process</option><option value="completed">Completed</option><option value="cancelled">Cancelled</option></select></div>
                            <div class="col-md-6"><label class="form-label" for="myTaskComments">Comments</label><textarea class="form-control" id="myTaskComments" name="regarding" rows="3" placeholder="Add comments"></textarea></div>
                        </div>
                    </section>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary"><i class="feather-check-square me-2"></i>Create Task</button></div>
            </form>
        </div>
    </div>

    <div class="modal fade professional-activity-modal" id="addEmailActivity" tabindex="-1" aria-labelledby="addEmailActivityLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <form class="modal-content" id="myEmailActivityForm" method="POST" action="{{ route('activities.store') }}" enctype="multipart/form-data">
                @csrf
                <input type="hidden" name="submission_token" value="{{ $submissionToken }}"><input type="hidden" name="return_to" value="myactivities"><input type="hidden" name="popup_type" value="email"><input type="hidden" name="activity_type_id" value="9"><input type="hidden" name="title" id="myEmailTitle"><input type="hidden" name="email_to" id="myEmailToValue"><input type="hidden" name="start_date" value="{{ now()->toDateString() }}"><input type="hidden" name="start_time" value="{{ now()->format('H:i') }}"><input type="hidden" name="end_date" value="{{ now()->toDateString() }}"><input type="hidden" name="end_time" value="{{ now()->addHour()->format('H:i') }}"><input type="hidden" name="lifecycle_status" value="planned">
                <div class="modal-header"><div class="d-flex align-items-center gap-3"><span class="call-modal-icon"><i class="feather-mail"></i></span><div><h5 class="modal-title fw-bold mb-1" id="addEmailActivityLabel">Create Email Activity</h5><p class="text-muted fs-12 mb-0">Compose, schedule, and track an email against a CRM record.</p></div></div><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div>
                <div class="modal-body">
                    @if ($errors->any() && old('popup_type') === 'email')<div class="alert alert-danger"><strong>The Email could not be created.</strong><ul class="mb-0 mt-2">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>@endif
                    <section class="call-modal-section"><div class="call-modal-section-title"><i class="feather-edit-3 text-primary"></i>Email Details</div><div class="row g-3">
                        <div class="col-12"><label class="form-label" for="myEmailSubject">Email Subject <span class="text-danger">*</span></label><input class="form-control" id="myEmailSubject" name="subject" maxlength="255" required placeholder="Enter email subject"></div>
                        <div class="col-md-6"><label class="form-label" for="myEmailFrom">From — Selected <span class="text-danger">*</span></label><x-activity-email-sender id="myEmailFrom" required /></div>
                        <div class="col-md-6"><label class="form-label" for="myEmailTo">To <span class="text-danger">*</span></label><select class="form-select" id="myEmailTo" multiple required data-placeholder="Select or enter recipients">@foreach($myEmailRecipientOptions as $recipient)<option value="{{ $recipient['email'] }}">{{ $recipient['label'] }}</option>@endforeach</select></div>
                        <div class="col-md-6"><label class="form-label" for="myEmailCc">CC</label><input class="form-control" id="myEmailCc" name="cc_recipients" placeholder="Comma-separated emails"></div><div class="col-md-6"><label class="form-label" for="myEmailBcc">BCC</label><input class="form-control" id="myEmailBcc" name="bcc_recipients" placeholder="Comma-separated emails"></div>
                        <div class="col-md-5"><label class="form-label" for="myEmailRelatedType">Related To <span class="text-danger">*</span></label><select class="form-select" id="myEmailRelatedType" required><option value="">Select module</option><option value="lead">Lead</option><option value="contact">Contact</option><option value="account">Account</option><option value="deal">Deal</option><option value="project">Project</option><option value="case">Case</option></select></div><div class="col-md-7"><label class="form-label" for="myEmailRelatedRecord">Related Record <span class="text-danger">*</span></label><select class="form-select" id="myEmailRelatedRecord" required disabled><option value="">Select record</option></select><div id="myEmailRelatedInputs"></div></div>
                    </div></section>
                    <section class="call-modal-section"><div class="call-modal-section-title"><i class="feather-settings text-primary"></i>Delivery &amp; Tracking</div><div class="row g-3">
                        <div class="col-md-6"><label class="form-label" for="myEmailOwner">Owner <span class="text-danger">*</span></label><select class="form-select" id="myEmailOwner" name="owner" required>@foreach($users as $user)<option value="{{ $user->id }}" @selected($user->id===auth()->id())>{{ $user->name }}</option>@endforeach</select></div><div class="col-md-6"><label class="form-label" for="myEmailTemplate">Email Template</label><select class="form-select" id="myEmailTemplate"><option value="">Select template</option>@foreach($emailTemplates as $template)<option value="{{ $template->id }}" data-subject="{{ $template->subject }}" data-body="{{ $template->body }}">{{ $template->name }}</option>@endforeach</select></div>
                        <div class="col-md-4"><label class="form-label" for="myEmailStatus">Status <span class="text-danger">*</span></label><select class="form-select" id="myEmailStatus" name="email_status" required><option value="draft">Draft</option><option value="sent">Sent</option><option value="opened">Opened</option><option value="replied">Replied</option><option value="failed">Failed</option></select></div><div class="col-md-4"><label class="form-label" for="myEmailSentAt">Sent Date &amp; Time</label><input class="form-control" id="myEmailSentAt" type="datetime-local" name="sent_at"></div><div class="col-md-4"><label class="form-label" for="myEmailScheduledAt">Scheduled to Send</label><input class="form-control" id="myEmailScheduledAt" type="datetime-local" name="scheduled_at"></div>
                    </div></section>
                    <section class="call-modal-section"><div class="call-modal-section-title"><i class="feather-file-text text-primary"></i>Message &amp; Attachments</div><div class="row g-3"><div class="col-12"><label class="form-label" for="myEmailComments">Comments / Email Body <span class="text-danger">*</span></label><textarea class="form-control" id="myEmailComments" name="email_body" rows="5" required placeholder="Write the email message"></textarea></div><div class="col-12"><label class="form-label" for="myEmailAttachment">Attachments</label><input class="form-control" id="myEmailAttachment" type="file" name="attachment" accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"><small class="text-muted">Attach a file up to 10 MB.</small></div></div></section>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary"><i class="feather-send me-2"></i>Create Email</button></div>
            </form>
        </div>
    </div>

    <div class="modal fade" id="addActivity" aria-labelledby="addActivityLabel" aria-hidden="true" x-data>
        <form id="createActivityForm" method="POST" action="{{ route('activities.store') }}" 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"
                            x-text="'Add ' + (Object.keys($store.activity.activityTypes).find(key => $store.activity.activityTypes[key] === $store.activity.selectedButton) ?? 'Select an 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" required>
                            </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="account_id_activity" id="hiddenAccountId">

                            <!-- Hidden Inputs for lead_id and deal_id -->
                            @if ($selectedLeadId)
                                <input type="hidden" name="lead_id" value="{{ $selectedLeadId }}">
                            @endif
                            @if ($selectedDealId)
                                <input type="hidden" name="deal_id" value="{{ $selectedDealId }}">
                            @endif

                            <!-- 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="scheduledCallFromInput"
                                        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> --}}




                            <!-- 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-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> --}}

                            <div class="col-lg-6 mb-4" x-data="{
                                selectedRelatedTo: '',
                                selectedLead: '',
                                selectedContact: '',
                                selectedDeal: '',
                                selectedAccount: '',
                                selectedButton: 2,
                                resetRelatedFields() {
                                    this.selectedLead = '';
                                    this.selectedContact = '';
                                    this.selectedDeal = '';
                                    this.selectedAccount = '';
                                }
                            }">
                                <!-- Main Dropdown -->
                                <div class="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"
                                            x-model="selectedRelatedTo">
                                            <option value="" 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>

                                <!-- Leads Dropdown -->
                                <div class="col-lg-14 mb-4"
                                    x-show="([2].includes($store.activity.selectedButton)) && selectedRelatedTo == 1"
                                    x-transition>
                                    <div class="input-group">
                                        <select class="form-control" name="lead_id" id="lead-dropdown"
                                            x-model="selectedLead">
                                            <option value="" disabled selected>Select Lead</option>
                                            @foreach ($leads as $lead)
                                                <option value="{{ $lead->id }}">{{ $lead->topic }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>

                                <!-- Contacts Dropdown -->
                                <div class="col-lg-14 mb-4"
                                    x-show="([2].includes($store.activity.selectedButton)) && selectedRelatedTo == 2"
                                    x-transition>
                                    <div class="input-group">
                                        <select class="form-control" name="contact_id" id="contact-dropdown"
                                            x-model="selectedContact">
                                            <option value="" disabled selected>Select Contact</option>
                                            @foreach ($contacts as $contact)
                                                <option value="{{ $contact->id }}">{{ $contact->first_name }}
                                                    {{ $contact->last_name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>

                                <!-- Deals Dropdown -->
                                <div class="col-lg-14 mb-4"
                                    x-show="([2].includes($store.activity.selectedButton)) && selectedRelatedTo == 3"
                                    x-transition>
                                    <div class="input-group">
                                        <select class="form-control" name="deal_id" id="deal-dropdown"
                                            x-model="selectedDeal">
                                            <option value="" disabled selected>Select Deal</option>
                                            @foreach ($deals as $deal)
                                                <option value="{{ $deal->id }}">{{ $deal->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>

                                <!-- Accounts Dropdown -->
                                <div class="col-lg-14 mb-4"
                                    x-show="([2].includes($store.activity.selectedButton)) && selectedRelatedTo == 4"
                                    x-transition>
                                    <div class="input-group">
                                        <select class="form-control" name="account_id" id="account-dropdown"
                                            x-model="selectedAccount">
                                            <option value="" disabled selected>Select Account</option>
                                            @foreach ($accounts as $account)
                                                <option value="{{ $account->id }}">{{ $account->account_name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <label class="block font-medium text-gray-700 mb-2">Direction</label>
                                <div class="input-group">
                                    <div class="flex items-center gap-4 justify-between">
                                        <label class="inline-flex items-center me-4">
                                            <input type="radio" class="form-radio text-blue-500" name="direction"
                                                value="Inbound" checked>
                                            <span class="ml-2">Inbound</span>
                                        </label>
                                        <label class="inline-flex items-center">
                                            <input type="radio" class="form-radio text-blue-500" name="direction"
                                                value="Outbound">
                                            <span class="ml-2">Outbound</span>
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <label class="block font-medium text-gray-700 mb-2">Call Status</label>
                                <div class="input-group">
                                    <div class="flex items-center gap-6"> <!-- Increased gap for better spacing -->
                                        <label class="inline-flex items-center me-2">
                                            <input type="radio" class="form-radio text-blue-500" name="call_status"
                                                value="Completed" checked>
                                            <span class="ml-2">Completed</span>
                                        </label>
                                        <label class="inline-flex items-center me-2">
                                            <input type="radio" class="form-radio text-blue-500" name="call_status"
                                                value="Scheduled">
                                            <span class="ml-2">Scheduled</span>
                                        </label>
                                        <label class="inline-flex items-center me-1">
                                            <input type="radio" class="form-radio text-blue-500" name="call_status"
                                                value="Current Call">
                                            <span class="ml-2">Current Call</span>
                                        </label>
                                    </div>
                                </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 src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const records = @json($myCallRecords->values());
            const typeSelect = document.getElementById('myCallRelatedType');
            const recordSelect = document.getElementById('myCallRelatedRecord');
            const relatedInputs = document.getElementById('myCallRelatedInputs');
            const form = document.getElementById('myCallActivityForm');

            function initialiseCallAssignees() {
                if (!window.jQuery || !jQuery.fn.select2) return;
                const assignees = jQuery('#myCallAssignees');
                if (assignees.hasClass('select2-hidden-accessible')) return;
                assignees.select2({
                    theme: 'bootstrap-5', width: '100%', closeOnSelect: false,
                    placeholder: 'Select one or more users',
                    dropdownParent: jQuery('#addCallActivity')
                });
            }

            function renderRelatedRecords() {
                recordSelect.innerHTML = '<option value="">Select record</option>';
                records.filter(record => record.type === typeSelect.value).forEach(record => recordSelect.add(new Option(record.label, record.id)));
                recordSelect.disabled = !typeSelect.value;
                syncRelatedRecord();
            }

            function syncRelatedRecord() {
                const record = records.find(item => item.type === typeSelect.value && Number(item.id) === Number(recordSelect.value));
                relatedInputs.innerHTML = '';
                document.getElementById('myCallOwnerName').value = record?.owner_name || '';
                document.getElementById('myCallOwnerId').value = record?.owner_id || @json((int) auth()->id());
                document.getElementById('myCallContactPerson').value = record?.contact_name || '';
                document.getElementById('myCallFrom').value = record?.contact_name || '';
                document.getElementById('myCallPhone').value = record?.phone || '';
                if (!record) return;

                const relation = document.createElement('input');
                relation.type = 'hidden'; relation.name = record.type + '_id'; relation.value = record.id;
                relatedInputs.appendChild(relation);
                if (record.type !== 'contact' && record.contact_id) {
                    const contact = document.createElement('input');
                    contact.type = 'hidden'; contact.name = 'contact_id'; contact.value = record.contact_id;
                    relatedInputs.appendChild(contact);
                }
            }

            function syncCallDateTime() {
                const value = document.getElementById('myCallDateTime').value;
                document.getElementById('myCallStartDate').value = value.slice(0, 10);
                document.getElementById('myCallEndDate').value = value.slice(0, 10);
                document.getElementById('myCallStartTime').value = value.slice(11, 16);
                document.getElementById('myCallEndTime').value = value.slice(11, 16);
            }

            typeSelect.addEventListener('change', renderRelatedRecords);
            recordSelect.addEventListener('change', syncRelatedRecord);
            document.getElementById('myCallDateTime').addEventListener('change', syncCallDateTime);
            form.addEventListener('submit', syncCallDateTime);
            document.getElementById('addCallActivity').addEventListener('shown.bs.modal', function () {
                syncCallDateTime();
                initialiseCallAssignees();
            });
            syncCallDateTime();
            @if ($errors->any() && old('popup_type') === 'call')
                bootstrap.Modal.getOrCreateInstance(document.getElementById('addCallActivity')).show();
            @endif
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const records = @json($myCallRecords->values());
            const typeSelect = document.getElementById('myMeetingRelatedType');
            const recordSelect = document.getElementById('myMeetingRelatedRecord');
            const relatedInputs = document.getElementById('myMeetingRelatedInputs');
            const form = document.getElementById('myMeetingActivityForm');

            function renderRecords() {
                recordSelect.innerHTML = '<option value="">Select record</option>';
                records.filter(record => record.type === typeSelect.value).forEach(record => recordSelect.add(new Option(record.label, record.id)));
                recordSelect.disabled = !typeSelect.value;
                syncRecord();
            }
            function syncRecord() {
                const record = records.find(item => item.type === typeSelect.value && Number(item.id) === Number(recordSelect.value));
                relatedInputs.innerHTML = '';
                if (!record) return;
                const relation = document.createElement('input'); relation.type = 'hidden'; relation.name = record.type + '_id'; relation.value = record.id; relatedInputs.appendChild(relation);
                if (record.type !== 'contact' && record.contact_id) {
                    const contact = document.createElement('input'); contact.type = 'hidden'; contact.name = 'contact_id'; contact.value = record.contact_id; relatedInputs.appendChild(contact);
                }
            }
            function localDate(date) { return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`; }
            function localTime(date) { return `${String(date.getHours()).padStart(2,'0')}:${String(date.getMinutes()).padStart(2,'0')}`; }
            function syncSchedule() {
                const start = new Date(document.getElementById('myMeetingDateTime').value);
                const end = new Date(start); end.setMinutes(end.getMinutes() + Number(document.getElementById('myMeetingDuration').value || 30));
                document.getElementById('myMeetingStartDate').value = localDate(start); document.getElementById('myMeetingStartTime').value = localTime(start);
                document.getElementById('myMeetingEndDate').value = localDate(end); document.getElementById('myMeetingEndTime').value = localTime(end);
            }
            function syncLocation() {
                const value = document.getElementById('myMeetingLocation').value;
                document.getElementById('myMeetingLocationLabel').value = value === 'customer_location' ? 'Customer Location' : (value ? value.charAt(0).toUpperCase() + value.slice(1) : '');
            }
            function initialiseAttendees() {
                if (!window.jQuery || !jQuery.fn.select2) return;
                const attendees = jQuery('#myMeetingAttendees');
                if (!attendees.hasClass('select2-hidden-accessible')) attendees.select2({ theme: 'bootstrap-5', width: '100%', closeOnSelect: false, placeholder: 'Select one or more employees', dropdownParent: jQuery('#addMeetingActivity') });
            }

            typeSelect.addEventListener('change', renderRecords); recordSelect.addEventListener('change', syncRecord);
            document.getElementById('myMeetingDateTime').addEventListener('change', syncSchedule);
            document.getElementById('myMeetingDuration').addEventListener('change', syncSchedule);
            document.getElementById('myMeetingLocation').addEventListener('change', syncLocation);
            form.addEventListener('submit', function () { syncSchedule(); syncLocation(); });
            document.getElementById('addMeetingActivity').addEventListener('shown.bs.modal', function () { syncSchedule(); syncLocation(); initialiseAttendees(); });
            syncSchedule(); syncLocation();
            @if ($errors->any() && old('popup_type') === 'meeting')
                bootstrap.Modal.getOrCreateInstance(document.getElementById('addMeetingActivity')).show();
            @endif
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const records = @json($myCallRecords->values());
            const typeSelect = document.getElementById('myTaskRelatedType');
            const recordSelect = document.getElementById('myTaskRelatedRecord');
            const relatedInputs = document.getElementById('myTaskRelatedInputs');
            const startDate = document.getElementById('myTaskStartDate');
            const dueDate = document.getElementById('myTaskDueDate');

            function renderRecords() {
                recordSelect.innerHTML = '<option value="">Select record</option>';
                records.filter(record => record.type === typeSelect.value).forEach(record => recordSelect.add(new Option(record.label, record.id)));
                recordSelect.disabled = !typeSelect.value;
                syncRecord();
            }
            function syncRecord() {
                const record = records.find(item => item.type === typeSelect.value && Number(item.id) === Number(recordSelect.value));
                relatedInputs.innerHTML = '';
                if (!record) return;
                const relation = document.createElement('input'); relation.type = 'hidden'; relation.name = record.type + '_id'; relation.value = record.id; relatedInputs.appendChild(relation);
                if (record.type !== 'contact' && record.contact_id) {
                    const contact = document.createElement('input'); contact.type = 'hidden'; contact.name = 'contact_id'; contact.value = record.contact_id; relatedInputs.appendChild(contact);
                }
            }
            function syncDates() {
                dueDate.min = startDate.value;
                if (dueDate.value && dueDate.value < startDate.value) dueDate.value = startDate.value;
                document.getElementById('myTaskEndDate').value = dueDate.value;
            }
            function initialiseAssignees() {
                if (!window.jQuery || !jQuery.fn.select2) return;
                const assignees = jQuery('#myTaskAssignees');
                if (!assignees.hasClass('select2-hidden-accessible')) assignees.select2({ theme: 'bootstrap-5', width: '100%', closeOnSelect: false, placeholder: 'Select one or more users', dropdownParent: jQuery('#addTaskActivity') });
            }

            typeSelect.addEventListener('change', renderRecords); recordSelect.addEventListener('change', syncRecord);
            startDate.addEventListener('change', syncDates); dueDate.addEventListener('change', syncDates);
            document.getElementById('myTaskActivityForm').addEventListener('submit', syncDates);
            document.getElementById('addTaskActivity').addEventListener('shown.bs.modal', initialiseAssignees);
            syncDates();
            @if ($errors->any() && old('popup_type') === 'task')
                bootstrap.Modal.getOrCreateInstance(document.getElementById('addTaskActivity')).show();
            @endif
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const records = @json($myCallRecords->values());
            const typeSelect = document.getElementById('myEmailRelatedType');
            const recordSelect = document.getElementById('myEmailRelatedRecord');
            const relatedInputs = document.getElementById('myEmailRelatedInputs');
            const recipients = document.getElementById('myEmailTo');
            const recipientValue = document.getElementById('myEmailToValue');
            const subject = document.getElementById('myEmailSubject');
            const status = document.getElementById('myEmailStatus');
            const sentAt = document.getElementById('myEmailSentAt');
            const scheduledAt = document.getElementById('myEmailScheduledAt');

            function renderRecords() { recordSelect.innerHTML = '<option value="">Select record</option>'; records.filter(record => record.type === typeSelect.value).forEach(record => recordSelect.add(new Option(record.label, record.id))); recordSelect.disabled = !typeSelect.value; syncRecord(); }
            function syncRecord() { const record = records.find(item => item.type === typeSelect.value && Number(item.id) === Number(recordSelect.value)); relatedInputs.innerHTML = ''; if (!record) return; const relation = document.createElement('input'); relation.type = 'hidden'; relation.name = record.type + '_id'; relation.value = record.id; relatedInputs.appendChild(relation); if (record.type !== 'contact' && record.contact_id) { const contact = document.createElement('input'); contact.type = 'hidden'; contact.name = 'contact_id'; contact.value = record.contact_id; relatedInputs.appendChild(contact); } }
            function syncRecipients() { recipientValue.value = Array.from(recipients.selectedOptions).map(option => option.value).join(', '); }
            const localNow = () => { const date = new Date(); date.setMinutes(date.getMinutes() - date.getTimezoneOffset()); return date.toISOString().slice(0,16); };
            function syncStatus() { if (status.value === 'draft') sentAt.value = ''; else if (!sentAt.value && !scheduledAt.value) sentAt.value = localNow(); }
            function initialiseRecipients() { if (!window.jQuery || !jQuery.fn.select2) return; const select = jQuery(recipients); if (!select.hasClass('select2-hidden-accessible')) select.select2({ theme: 'bootstrap-5', width: '100%', multiple: true, tags: true, closeOnSelect: false, tokenSeparators: [',',';'], placeholder: 'Select or enter recipients', dropdownParent: jQuery('#addEmailActivity') }).on('change', syncRecipients); }

            typeSelect.addEventListener('change', renderRecords); recordSelect.addEventListener('change', syncRecord); recipients.addEventListener('change', syncRecipients);
            status.addEventListener('change', syncStatus); scheduledAt.addEventListener('change', function () { if (!this.value) return; status.value = 'draft'; sentAt.value = ''; });
            document.getElementById('myEmailTemplate').addEventListener('change', function () { const option = this.options[this.selectedIndex]; if (!option.value) return; subject.value = option.dataset.subject || ''; document.getElementById('myEmailComments').value = option.dataset.body || ''; });
            document.getElementById('myEmailActivityForm').addEventListener('submit', function () { syncRecipients(); document.getElementById('myEmailTitle').value = subject.value; });
            document.getElementById('addEmailActivity').addEventListener('shown.bs.modal', initialiseRecipients);
            @if ($errors->any() && old('popup_type') === 'email')
                bootstrap.Modal.getOrCreateInstance(document.getElementById('addEmailActivity')).show();
            @endif
        });
    </script>

    <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('[data-activity-type]').forEach(function(element) {
                element.addEventListener('click', function() {
                    const selectedId = this.getAttribute('data-activity-type');
                    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;

                    // 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>
    {{-- <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.ticket-list').forEach(function(list) {
                let sortable = new Sortable(list, {
                    group: 'shared',
                    animation: 150,
                    onEnd(evt) {
                        let ticketId = evt.item.getAttribute('data-ticket-id');

                        let newStageId = evt.item.closest('td').getAttribute('data-stage-id');

                        console.log("Ticket ID:", ticketId);
                        console.log("New Stage ID:", newStageId);

                        if (evt.from !== evt.to) {
                            fetch(`/tickets/${ticketId}/update-ticket-stage`, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                        'X-CSRF-TOKEN': document.querySelector(
                                            'meta[name="csrf-token"]').getAttribute(
                                            'content')
                                    },
                                    body: JSON.stringify({
                                        stage_id: newStageId
                                    })
                                })
                                .then(response => response.json())
                                .then(data => {
                                    console.log('Ticket stage updated', data);
                                })
                                .catch(error => console.error('Error updating ticket stage:',
                                    error));
                        }
                    }
                });
            });
        });
    </script> --}}
@endsection
