@php
    $isEdit = isset($deal) && $deal->exists;
    $selectedPrimaryAccount = (int) old('primary_account', $isEdit ? ($deal->account_id ?: $deal->accounts->first()?->id) : 0);
    $selectedContacts = old('contact_ids', $isEdit
        ? $deal->contacts->pluck('id')->whenEmpty(fn($ids) => $deal->contact_id ? collect([$deal->contact_id]) : collect())->all()
        : array_filter([$selectedContactId ?? null]));
    $dealProductLines = $dealProductLines ?? collect();
    $lines = $isEdit && $dealProductLines->isNotEmpty() ? $dealProductLines : collect([null]);
    $currencyId = (int) old('currency', $deal->currency_id ?? 1);
    $lastInteractionText = ($lastInteraction ?? null)?->updated_at?->format('d M Y, h:i A') ?? 'No interaction recorded';
@endphp

<div class="deal-form-intro"><span><i class="feather-briefcase"></i></span><div><h5>{{ $isEdit ? 'Update Deal Information' : 'New Deal Information' }}</h5><p>Maintain the opportunity, pricing, document workflow and closing plan.</p></div></div>

@if($errors->any())<div class="alert alert-danger mx-4 mt-4 mb-0"><strong>Please review the highlighted fields.</strong><ul class="mb-0 mt-2">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>@endif

<div class="card-body deal-form-body">
    <div class="deal-form-section"><div><i class="feather-compass"></i><strong>Deal Details</strong></div><small>Required identity, ownership and customer relationships.</small></div>
    <div class="row deal-form-grid">
        <div class="col-md-6"><label>Deal Name <span>*</span></label><div class="input-group"><span class="input-group-text"><i class="feather-tag"></i></span><input class="form-control @error('deal_name') is-invalid @enderror" name="deal_name" value="{{ old('deal_name',$deal->name??request('name')) }}" required maxlength="255" placeholder="Enter Deal name"></div></div>
        <div class="col-md-6"><label>Deal Owner <span>*</span></label><div class="input-group"><span class="input-group-text"><i class="feather-user-check"></i></span><select class="form-select" id="dealOwner" name="lead_owner" required>@foreach($users as $user)<option value="{{ $user->id }}" @selected((int)old('lead_owner',$deal->owner_id??auth()->id())===$user->id)>{{ $user->name }}</option>@endforeach</select></div></div>
        <div class="col-md-6"><label>Deal Source</label><div class="input-group"><span class="input-group-text"><i class="feather-zap"></i></span><select class="form-select" name="lead_name"><option value="">Select Lead</option>@foreach($leads as $lead)<option value="{{ $lead->id }}" @selected((int)old('lead_name',$deal->lead_id??$selectedLeadId??0)===$lead->id)>{{ $lead->topic ?: trim($lead->first_name.' '.$lead->last_name) ?: 'Lead #'.$lead->id }}</option>@endforeach</select></div></div>
        <div class="col-md-6"><label>Primary Account</label><div class="input-group"><span class="input-group-text"><i class="feather-home"></i></span><select class="form-select @error('primary_account') is-invalid @enderror" name="primary_account"><option value="">Select Primary Account</option>@foreach($accounts as $account)<option value="{{ $account->id }}" @selected($selectedPrimaryAccount === (int) $account->id)>{{ $account->account_name }}</option>@endforeach</select></div><small class="text-muted">The selected Account becomes the primary Account for this Deal.</small></div>
        <div class="col-md-6"><label>Contacts <span>*</span></label><div class="input-group"><span class="input-group-text"><i class="feather-users"></i></span><select class="form-select @error('primary_contact') is-invalid @enderror" id="dealContacts" name="contact_ids[]" multiple required data-placeholder="Search Contacts by name">@foreach($contacts as $contact)<option value="{{ $contact->id }}" data-owner-id="{{ $contact->contact_owner_id }}" data-owner-name="{{ $contact->assignedUser?->name ?? 'Unassigned' }}" @selected(in_array($contact->id,$selectedContacts))>{{ trim($contact->first_name.' '.$contact->last_name) ?: 'Contact #'.$contact->id }} · Owner: {{ $contact->assignedUser?->name ?? 'Unassigned' }}</option>@endforeach</select></div><small class="text-muted">Search shows Contacts assigned to the selected Deal Owner. The first selection is primary.</small><input type="hidden" id="primaryContact" name="primary_contact" value="{{ old('primary_contact',$deal->contact_id??$selectedContactId??'') }}"></div>
        <div class="col-md-6"><label>Time Frame</label><div class="input-group"><span class="input-group-text"><i class="feather-clock"></i></span><select class="form-select" name="time_frame"><option value="">Select Time Frame</option>@foreach([1=>'Immediate',2=>'1–3 Months',3=>'3–6 Months',4=>'6–12 Months',5=>'More than a Year'] as $id=>$label)<option value="{{ $id }}" @selected((int)old('time_frame',$deal->time_frame_id??0)===$id)>{{ $label }}</option>@endforeach</select></div></div>
        <div class="col-md-6"><label>Deal Type <span>*</span></label><div class="input-group"><span class="input-group-text"><i class="feather-layers"></i></span><select class="form-select" name="deal_type" required><option value="">Select Deal Type</option><option value="new_business" @selected(old('deal_type',$deal->deal_type??'')==='new_business')>New Business</option><option value="existing_business" @selected(old('deal_type',$deal->deal_type??'')==='existing_business')>Existing Business</option></select></div></div>
        <div class="col-md-6"><label>Currency <span>*</span></label><div class="input-group"><span class="input-group-text"><i class="feather-dollar-sign"></i></span><select class="form-select" id="currency-dropdown" name="currency" required>@foreach(\App\Models\Deal::$currencies as $id=>$name)<option value="{{ $id }}" data-code="{{ substr($name,0,3) }}" @selected($currencyId===$id)>{{ $name }}</option>@endforeach</select></div></div>
    </div>

    <div class="deal-form-section"><div><i class="feather-shopping-bag"></i><strong>Inventory</strong></div><small>Add products with row-level pricing, discounts and tax.</small></div>
    <div class="deal-inventory-shell">
        <div class="table-responsive"><table class="table deal-inventory-table" id="dealInventory"><thead><tr><th>#</th><th>Product</th><th>Unit</th><th>Qty</th><th>Unit Price</th><th>Discount %</th><th>Tax %</th><th>Line Total</th><th></th></tr></thead><tbody>
        @foreach($lines as $line)<tr class="inventory-line"><td><span class="row-number">{{ $loop->iteration }}</span></td><td><select class="form-select product-select" name="product[]"><option value="">Select Product</option>@foreach($products as $product)<option value="{{ $product->id }}" @selected((int)($line?->product_id??0)===$product->id)>{{ $product->product_name }}</option>@endforeach</select></td><td><select class="form-select" name="unit[]">@foreach([1=>'Pcs',2=>'Kg',3=>'Ltr'] as $id=>$name)<option value="{{ $id }}" @selected((int)($line?->unit_id??1)===$id)>{{ $name }}</option>@endforeach</select></td><td><input class="form-control qty" type="number" min="1" step="1" name="qty[]" value="{{ $line?->quantity??1 }}"></td><td><input class="form-control price" type="number" min="0" step=".01" name="price[]" value="{{ $line?->product_price }}"></td><td><input class="form-control discount" type="number" min="0" max="100" step=".01" name="discount[]" value="{{ $line?->discount??0 }}"></td><td><input class="form-control tax" type="number" min="0" max="100" step=".01" name="tax[]" value="{{ $line?->tax??0 }}"></td><td><input class="form-control line-total" type="number" name="total[]" value="{{ $line?->line_total??0 }}" readonly></td><td><div class="row-actions"><button type="button" class="row-add" title="Add row"><i class="feather-plus"></i></button><button type="button" class="row-remove" title="Remove row"><i class="feather-trash-2"></i></button></div></td></tr>@endforeach
        </tbody></table></div>
        <p class="inventory-help"><i class="feather-info"></i>Use the plus icon to insert a new product row.</p>
        <div class="inventory-summary"><div><span>Sub Total</span><input id="sub_total" name="sub_total" readonly></div><div><span>Discount</span><input id="total_discount" name="total_discount" type="number" min="0" step=".01" value="{{ old('total_discount',$deal->discount??0) }}"></div><div><span>Tax</span><input id="total_tax" name="total_tax" type="number" min="0" step=".01" value="{{ old('total_tax',$deal->tax??0) }}"></div><div class="grand"><span>Grand Total</span><input id="grand_total" name="grand_total" readonly></div><input type="hidden" id="total_amount" name="total_amount"></div>
    </div>

    <div class="deal-form-section"><div><i class="feather-trending-up"></i><strong>Value &amp; Timeline</strong></div><small>Expected revenue, probability and customer interaction timing.</small></div>
    <div class="row deal-form-grid">
        <div class="col-md-6"><label>Deal Value</label><div class="input-group"><span class="input-group-text"><i class="feather-credit-card"></i></span><input class="form-control" id="dealValue" readonly></div></div>
        <div class="col-md-6"><label>Expected Close Date <span>*</span></label><div class="input-group"><span class="input-group-text"><i class="feather-calendar"></i></span><input class="form-control" type="date" name="closing_date" value="{{ old('closing_date',optional($deal->closing_date??null)->format('Y-m-d')) }}" required></div></div>
        <div class="col-md-6"><label>Create Date</label><div class="input-group"><span class="input-group-text"><i class="feather-calendar"></i></span><input class="form-control" type="datetime-local" name="create_date" value="{{ old('create_date',isset($deal)?optional($deal->create_date)->format('Y-m-d\TH:i'):now()->format('Y-m-d\TH:i')) }}" required></div></div>
        <div class="col-md-6"><label>Close Probability</label><div class="input-group"><span class="input-group-text"><i class="feather-percent"></i></span><input class="form-control" id="closeProbability" type="number" min="0" max="100" name="close_probability" value="{{ old('close_probability',$deal->close_probability??0) }}"></div></div>
        <div class="col-md-6"><label>Forecast Value</label><div class="input-group"><span class="input-group-text"><i class="feather-bar-chart-2"></i></span><input class="form-control" id="forecastValue" readonly></div></div>
        <div class="col-md-6"><label>Last Interaction</label><div class="input-group"><span class="input-group-text"><i class="feather-activity"></i></span><input class="form-control" value="{{ $lastInteractionText }}" readonly></div></div>
    </div>

    <div class="deal-form-section"><div><i class="feather-file-text"></i><strong>Trade Document</strong></div><small>Choose the output type and a compatible branded template.</small></div>
    <div class="row deal-form-grid">
        <div class="col-md-6"><label>Trade Type</label><div class="input-group"><span class="input-group-text"><i class="feather-file"></i></span><select class="form-select" id="tradeType" name="trade_type"><option value="">None</option>@foreach(['quotation'=>'Quotation','invoice'=>'Invoice','proposal'=>'Proposal'] as $value=>$label)<option value="{{ $value }}" @selected(old('trade_type',$deal->trade_type??'')===$value)>{{ $label }}</option>@endforeach</select></div></div>
        <div class="col-md-6"><label>Document Template</label><div class="input-group"><span class="input-group-text"><i class="feather-layout"></i></span><select class="form-select" id="documentTemplate" name="document_template_id"><option value="">Default Template</option>@foreach($documentTemplates as $template)<option value="{{ $template->id }}" data-type="{{ $template->type }}" @selected((int)old('document_template_id',$deal->document_template_id??0)===$template->id)>{{ $template->name }} · {{ ucfirst($template->type) }}</option>@endforeach</select></div></div>
        <div class="col-md-6"><label>Validity Period</label><div class="input-group"><span class="input-group-text"><i class="feather-calendar"></i></span><input class="form-control" type="date" name="valid_until" value="{{ old('valid_until',optional($deal->valid_until??null)->format('Y-m-d')) }}"></div></div>
        <div class="col-md-6"><label>Billing Frequency</label><div class="input-group"><span class="input-group-text"><i class="feather-repeat"></i></span><select class="form-select" name="billing_frequency"><option value="">None</option>@foreach($billing_frequencies as $frequency)<option value="{{ $frequency->id }}" @selected((int)old('billing_frequency',$deal->billing_frequency_id??0)===$frequency->id)>{{ $frequency->name }}</option>@endforeach</select></div></div>
        <div class="col-md-6"><label>Billing Repeat</label><div class="input-group"><span class="input-group-text"><i class="feather-refresh-cw"></i></span><input class="form-control" type="number" min="1" max="999" name="billing_repeat" value="{{ old('billing_repeat',$deal->billing_frequency_repeat_status??1) }}"></div></div>
        <div class="col-md-6"><label>Stage</label><div class="input-group"><span class="input-group-text"><i class="feather-git-commit"></i></span><select class="form-select" name="stage_id" required>@foreach($stages as $stage)@continue($stage->id>8)<option value="{{ $stage->id }}" @selected((int)old('stage_id',$deal->stage_id??1)===$stage->id)>{{ $stage->name }}</option>@endforeach</select></div></div>
        <div class="col-12"><label>Comments</label><textarea class="form-control" name="comments" rows="4" placeholder="Add Deal or document comments">{{ old('comments',$deal->comments??'') }}</textarea></div>
    </div>
</div>

<div class="deal-form-actions">
    <div class="document-actions"><button class="btn btn-outline-warning" name="after_save" value="approval"><i class="feather-shield"></i> Send Approval</button><button class="btn btn-outline-info" name="after_save" value="customer"><i class="feather-mail"></i> Send Customer</button><button class="btn btn-outline-success" name="after_save" value="sent"><i class="feather-send"></i> Sent</button><button class="btn btn-outline-dark" name="after_save" value="print"><i class="feather-printer"></i> Print</button></div>
    <div class="save-actions"><a class="btn btn-light" href="{{ route('deals') }}"><i class="feather-x"></i> Cancel</a><button class="btn btn-primary" name="after_save" value="save"><i class="feather-save"></i> Save</button></div>
</div>
