<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Edit Call | CRM</title>
    <link rel="shortcut icon" type="image/x-icon" href="{{ asset('assets/images/favicon.ico') }}">
    <link rel="stylesheet" href="{{ asset('assets/css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ asset('assets/vendors/css/vendors.min.css') }}">
    <link rel="stylesheet" href="{{ asset('assets/css/theme.min.css') }}">
    <style>
        .call-edit-page { min-height: 100vh; background: #f5f7fb; }
        .call-edit-wrap { max-width: 1120px; margin: 0 auto; padding: 28px 24px 60px; }
        .call-page-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 20px; }
        .call-page-heading h1 { margin: 0 0 5px; color: #1d2939; font-size: 25px; font-weight: 800; }
        .call-page-heading p { margin: 0; color: #667085; }
        .call-card { overflow: hidden; border: 1px solid #e4e9f1; border-radius: 16px; background: #fff; box-shadow: 0 12px 34px rgba(16,24,40,.06); }
        .call-card-header { display: flex; align-items: center; gap: 14px; padding: 22px 24px; border-bottom: 1px solid #e9edf3; background: linear-gradient(135deg,#f8faff 0%,#fff 70%); }
        .call-card-icon { display: grid; width: 46px; height: 46px; place-items: center; border-radius: 12px; background: #3454d1; color: #fff; font-size: 20px; box-shadow: 0 8px 20px rgba(52,84,209,.22); }
        .call-card-header h2 { margin: 0 0 3px; color: #202939; font-size: 17px; font-weight: 800; }
        .call-card-header p { margin: 0; color: #7a8699; font-size: 13px; }
        .call-card-body { padding: 24px; }
        .call-section { margin-bottom: 22px; padding-bottom: 20px; border-bottom: 1px solid #edf0f4; }
        .call-section:last-of-type { margin-bottom: 0; padding-bottom: 0; border-bottom: 0; }
        .call-section-title { display: flex; align-items: center; gap: 8px; margin-bottom: 15px; color: #344054; font-size: 13px; font-weight: 800; text-transform: uppercase; letter-spacing: .035em; }
        .form-label { margin-bottom: 7px; color: #344054; font-size: 12px; font-weight: 700; }
        .form-control, .form-select { min-height: 44px; border-color: #dce2eb; border-radius: 9px; color: #344054; }
        textarea.form-control { min-height: 108px; }
        .form-control:focus, .form-select:focus { border-color: #7890eb; box-shadow: 0 0 0 3px rgba(52,84,209,.11); }
        .select2-container { width: 100% !important; }
        .select2-container .select2-selection--multiple { min-height: 44px; padding: 4px 7px; border-color: #dce2eb; border-radius: 9px; }
        .select2-container .select2-selection--multiple .select2-selection__choice { margin-top: 4px; border: 0; border-radius: 6px; background: #e9edff; color: #3454d1; font-weight: 650; }
        .readonly-field { background: #f8fafc !important; color: #667085; }
        .call-actions { display: flex; justify-content: flex-end; gap: 10px; margin: 24px -24px -24px; padding: 16px 24px; border-top: 1px solid #e8ecf2; background: #fbfcfe; }
        .required-mark { color: #e5484d; }
        @media (max-width: 767px) { .call-edit-wrap { padding: 18px 12px 40px; } .call-page-heading { flex-direction: column; } .call-card-body { padding: 18px; } }
    </style>
</head>
<body>
@include('layouts.sidebar')
@include('layouts.header')

@php
    $contactById = $contacts->keyBy('id');
    $allowedOwnerIds = $users->pluck('id')->map(fn ($id) => (int) $id);
    $callRecords = collect();
    $addRecord = function ($type, $record, $label, $contact, $owner, $phone = null) use ($callRecords, $allowedOwnerIds) {
        $ownerId = $owner?->id && $allowedOwnerIds->contains((int) $owner->id) ? (int) $owner->id : (int) auth()->id();
        $callRecords->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 = $contactById->get($lead->primary_contact_id);
        $addRecord('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) $addRecord('contact', $contact, trim($contact->first_name.' '.$contact->last_name) ?: 'Contact #'.$contact->id, $contact, $contact->assignedUser, $contact->contactPhones->first()?->phone);
    foreach ($accounts as $account) $addRecord('account', $account, $account->account_name ?: 'Account #'.$account->id, $account->primaryContact, $account->assignedUser, $account->contactPhones->first()?->phone);
    foreach ($deals as $deal) $addRecord('deal', $deal, $deal->name ?: 'Deal #'.$deal->id, $deal->contact, $deal->assignedUser, $deal->contactPhones->first()?->phone);
    foreach ($cases as $case) {
        $contact = $case->contact ?: $case->deal?->contact ?: $case->account?->primaryContact ?: $contactById->get($case->lead?->primary_contact_id);
        $addRecord('case', $case, trim(($case->case_number ?: 'Case #'.$case->id).' — '.$case->subject), $contact, $case->assignee, $contact?->contactPhones?->first()?->phone ?: $case->lead?->contactPhones?->first()?->phone);
    }
    $relatedType = $scheduledActivity->lead_id ? 'lead' : ($scheduledActivity->deal_id ? 'deal' : ($scheduledActivity->account_id ? 'account' : ($scheduledActivity->case_id ? 'case' : 'contact')));
    $relatedId = $scheduledActivity->{$relatedType.'_id'};
    $selectedAssignees = old('assignee_ids', $scheduledActivity->assignees->pluck('id')->all() ?: [$scheduledActivity->owner_id]);
    $callDateTimeValue = $scheduledActivity->start_date
        ? \Carbon\Carbon::parse($scheduledActivity->start_date.' '.($scheduledActivity->start_time ?: '09:00'))->format('Y-m-d\TH:i')
        : now()->format('Y-m-d\TH:i');
@endphp

<main class="nxl-container call-edit-page">
    <div class="nxl-content">
        <div class="call-edit-wrap">
            <div class="call-page-heading">
                <div><h1>Edit Call</h1><p>Update call information and its related CRM record.</p></div>
                <a href="{{ route('schedule-activity') }}" class="btn btn-light"><i class="feather-arrow-left me-2"></i>Back to Activities</a>
            </div>

            @if ($errors->any())
                <div class="alert alert-danger"><strong>Please correct the following:</strong><ul class="mb-0 mt-2">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>
            @endif

            <form method="POST" action="{{ route('activities.update', $scheduledActivity->id) }}" id="callEditForm" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <input type="hidden" name="activity_type_id" value="1">
                <input type="hidden" name="status" value="{{ $scheduledActivity->status ?: 'active' }}">
                <input type="hidden" name="visibility" value="{{ $scheduledActivity->visibility ?: 'team' }}">

                <div class="call-card">
                    <div class="call-card-header">
                        <div class="call-card-icon"><i class="feather-phone-call"></i></div>
                        <div><h2>Call Information</h2><p>Only fields relevant to this Call are displayed.</p></div>
                    </div>
                    <div class="call-card-body">
                        <section class="call-section">
                            <div class="call-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="callSubject">Call Subject <span class="required-mark">*</span></label><input class="form-control" id="callSubject" name="title" value="{{ old('title', $scheduledActivity->title) }}" maxlength="255" required></div>
                                <div class="col-md-5"><label class="form-label" for="relatedType">Related To <span class="required-mark">*</span></label><select class="form-select" id="relatedType" 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="relatedRecord">Related Record <span class="required-mark">*</span></label><select class="form-select" id="relatedRecord" required><option value="">Select record</option></select><div id="relatedHiddenInputs"></div></div>
                                <div class="col-md-6"><label class="form-label">Contact Owner</label><input class="form-control readonly-field" id="contactOwner" readonly><input type="hidden" name="owner" id="ownerId" value="{{ $scheduledActivity->owner_id }}"></div>
                                <div class="col-md-6"><label class="form-label">Contact Person</label><input class="form-control readonly-field" id="contactPerson" readonly><input type="hidden" name="callFrom" id="callFrom"></div>
                                <div class="col-md-6"><label class="form-label" for="phoneNumber">Phone Number From <span class="required-mark">*</span></label><input class="form-control" id="phoneNumber" name="phoneNumber" value="{{ old('phoneNumber', $scheduledActivity->phone_number) }}" required></div>
                                <div class="col-md-6"><label class="form-label" for="direction">Call Type <span class="required-mark">*</span></label><select class="form-select" id="direction" name="direction" required><option value="">Select call type</option><option value="inbound" @selected(old('direction',$scheduledActivity->direction)==='inbound')>Incoming</option><option value="outbound" @selected(old('direction',$scheduledActivity->direction)==='outbound')>Outgoing</option></select></div>
                            </div>
                        </section>

                        <section class="call-section">
                            <div class="call-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="assignees">Assigned To <span class="required-mark">*</span></label><select class="form-select" id="assignees" name="assignee_ids[]" multiple required data-placeholder="Select one or more users">@foreach($users as $user)<option value="{{ $user->id }}" @selected(in_array($user->id,$selectedAssignees))>{{ $user->name }}</option>@endforeach</select></div>
                                <div class="col-md-6"><label class="form-label" for="callDateTime">Call Date &amp; Time <span class="required-mark">*</span></label><input class="form-control" id="callDateTime" type="datetime-local" value="{{ old('call_datetime', $callDateTimeValue) }}" required><input type="hidden" name="start_date" id="startDate"><input type="hidden" name="start_time" id="startTime"><input type="hidden" name="end_date" id="endDate"><input type="hidden" name="end_time" id="endTime"></div>
                                <div class="col-md-6"><label class="form-label" for="reminder">Reminder</label><input class="form-control" id="reminder" type="datetime-local" name="remind_at" value="{{ old('remind_at', $scheduledActivity->remind_at?->format('Y-m-d\TH:i')) }}"></div>
                                <div class="col-md-6"><label class="form-label" for="callEscalation">Escalation After</label><select class="form-select" id="callEscalation" name="reminder_escalation_hours">@foreach([4,12,24,48,72] as $hours)<option value="{{ $hours }}" @selected((int) old('reminder_escalation_hours',$scheduledActivity->reminder_escalation_hours ?: 24)===$hours)>{{ $hours }} hours</option>@endforeach</select></div>
                                <div class="col-md-6"><label class="form-label" for="duration">Duration <span class="required-mark">*</span></label><input class="form-control" id="duration" name="duration" value="{{ old('duration',$scheduledActivity->duration) }}" required placeholder="e.g. 15 minutes"></div>
                                <div class="col-md-6"><label class="form-label" for="lifecycleStatus">Status <span class="required-mark">*</span></label><select class="form-select" id="lifecycleStatus" name="lifecycle_status" required>@foreach(['planned'=>'Planned','open'=>'Open','in_progress'=>'In Progress','completed'=>'Completed','cancelled'=>'Cancelled'] as $value=>$label)<option value="{{ $value }}" @selected(old('lifecycle_status',$scheduledActivity->lifecycle_status)===$value)>{{ $label }}</option>@endforeach</select></div>
                                <div class="col-md-6"><label class="form-label" for="outcome">Outcome <span class="required-mark">*</span></label><select class="form-select" id="outcome" name="outcome" required><option value="">Select outcome</option><option value="interested" @selected(old('outcome',$scheduledActivity->outcome)==='interested')>Interested</option><option value="follow_up_required" @selected(old('outcome',$scheduledActivity->outcome)==='follow_up_required')>Follow-up Required</option><option value="not_interested" @selected(old('outcome',$scheduledActivity->outcome)==='not_interested')>Not Interested</option></select></div>
                            </div>
                        </section>

                        <section class="call-section">
                            <div class="call-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="notes">Note</label><textarea class="form-control" id="notes" name="description">{{ old('description',$scheduledActivity->description) }}</textarea></div>
                                <div class="col-12"><label class="form-label" for="callEvidence">Evidence Attachment</label><input class="form-control" id="callEvidence" type="file" name="attachment" accept="image/*,audio/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"><small class="text-muted">Attach new supporting evidence up to 10 MB.</small></div>
                            </div>
                        </section>

                        <div class="call-actions"><a href="{{ route('schedule-activity') }}" class="btn btn-light">Cancel</a><button class="btn btn-primary" type="submit"><i class="feather-save me-2"></i>Update Call</button></div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</main>

<script src="{{ asset('assets/vendors/js/vendors.min.js') }}"></script>
<script src="{{ asset('assets/js/common-init.min.js') }}"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    if (window.jQuery && jQuery.fn.select2) {
        jQuery('#assignees').select2({ theme: 'bootstrap-5', width: '100%', closeOnSelect: false, placeholder: 'Select one or more users' });
    }
    const records = @json($callRecords->values());
    const initialType = @json(old('related_type', $relatedType));
    const initialId = Number(@json(old('related_id', $relatedId)) || 0);
    const relatedType = document.getElementById('relatedType');
    const relatedRecord = document.getElementById('relatedRecord');
    const phone = document.getElementById('phoneNumber');
    let firstSync = true;

    function recordsForType() { return records.filter(record => record.type === relatedType.value); }
    function renderRecords(selectedId) {
        relatedRecord.innerHTML = '<option value="">Select record</option>';
        recordsForType().forEach(record => relatedRecord.add(new Option(record.label, record.id, false, Number(record.id) === Number(selectedId))));
        syncRecord();
    }
    function syncRecord() {
        const record = records.find(item => item.type === relatedType.value && Number(item.id) === Number(relatedRecord.value));
        document.getElementById('relatedHiddenInputs').innerHTML = '';
        document.getElementById('contactOwner').value = record?.owner_name || '';
        document.getElementById('contactPerson').value = record?.contact_name || '';
        document.getElementById('ownerId').value = record?.owner_id || @json((int) auth()->id());
        document.getElementById('callFrom').value = record?.contact_name || '';
        if (record) {
            const relatedInput = document.createElement('input'); relatedInput.type = 'hidden'; relatedInput.name = record.type + '_id'; relatedInput.value = record.id;
            document.getElementById('relatedHiddenInputs').appendChild(relatedInput);
            if (record.type !== 'contact' && record.contact_id) {
                const contactInput = document.createElement('input'); contactInput.type = 'hidden'; contactInput.name = 'contact_id'; contactInput.value = record.contact_id;
                document.getElementById('relatedHiddenInputs').appendChild(contactInput);
            }
            if (!firstSync || !phone.value) phone.value = record.phone || '';
        }
        firstSync = false;
    }
    function syncDateTime() {
        const value = document.getElementById('callDateTime').value;
        document.getElementById('startDate').value = value.slice(0,10); document.getElementById('endDate').value = value.slice(0,10);
        document.getElementById('startTime').value = value.slice(11,16); document.getElementById('endTime').value = value.slice(11,16);
    }
    relatedType.value = initialType; renderRecords(initialId);
    relatedType.addEventListener('change', () => renderRecords(0)); relatedRecord.addEventListener('change', syncRecord);
    document.getElementById('callDateTime').addEventListener('change', syncDateTime); syncDateTime();
    document.getElementById('callEditForm').addEventListener('submit', syncDateTime);
});
</script>
</body>
</html>
