<p-toast />
<p-confirmDialog />

<div class="bills-page">
  <app-page-header title="PURCHASES.BILLS" subtitle="PURCHASES.TITLE" (refresh)="retry()">
    <p-button [label]="'PURCHASES.NEW_BILL' | translate" icon="pi pi-plus" (onClick)="openNew()" />
  </app-page-header>

  <!-- Quick Stats Bar -->
  <div class="stats-bar">
    <div class="stat-card outstanding">
      <div class="stat-icon"><i class="pi pi-wallet"></i></div>
      <div class="stat-info">
        <span class="stat-label">{{ 'PURCHASES.TOTAL_OUTSTANDING' | translate }}</span>
        <span class="stat-value">{{ totalOutstanding() | number:'1.2-2' }}</span>
      </div>
    </div>
    <div class="stat-card overdue">
      <div class="stat-icon"><i class="pi pi-exclamation-triangle"></i></div>
      <div class="stat-info">
        <span class="stat-label">{{ 'PURCHASES.OVERDUE_AMOUNT' | translate }}</span>
        <span class="stat-value">{{ overdueAmount() | number:'1.2-2' }}</span>
      </div>
    </div>
  </div>

  <ng-template #bodyTpl let-b>
    <tr [class.overdue-row]="isOverdue(b)">
      <td class="mono">{{ b.bill_number }}</td>
      <td>{{ b.date }}</td>
      <td [class.text-danger]="isOverdue(b)">
        {{ b.due_date }}
        @if (isOverdue(b)) {
          <i class="pi pi-exclamation-circle text-danger" style="margin-inline-start: 4px; font-size: 0.75rem;"></i>
        }
      </td>
      <td>{{ b.supplier_name }}</td>
      <td>{{ b.supplier_invoice_number || '-' }}</td>
      <td class="amount">{{ b.total | number:'1.2-2' }}</td>
      <td class="amount">{{ b.amount_paid | number:'1.2-2' }}</td>
      <td class="amount" [class.text-danger]="isOverdue(b)">{{ b.balance_due | number:'1.2-2' }}</td>
      <td>
        <p-tag [value]="getStatusLabel(b.status)" [severity]="getStatusSeverity(b.status)" />
      </td>
      <td>
        <div class="action-buttons">
          <p-button icon="pi pi-eye" [rounded]="true" [text]="true" severity="info" (onClick)="viewBill(b)" [pTooltip]="'COMMON.VIEW' | translate" />
          @if (b.status === 'draft') {
            <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" (onClick)="editBill(b)" [pTooltip]="'COMMON.EDIT' | translate" />
            <p-button icon="pi pi-send" [rounded]="true" [text]="true" severity="warn" (onClick)="submitApproval(b)" [pTooltip]="'PURCHASES.SUBMIT_APPROVAL' | translate" />
            <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" (onClick)="deleteBill(b)" [pTooltip]="'COMMON.DELETE' | translate" />
          }
          @if (b.status === 'pending_approval') {
            <p-button icon="pi pi-check" [rounded]="true" [text]="true" severity="success" (onClick)="approveBill(b)" [pTooltip]="'PURCHASES.APPROVE' | translate" />
          }
          @if (b.status === 'approved') {
            <p-button icon="pi pi-upload" [rounded]="true" [text]="true" severity="success" (onClick)="postBill(b)" [pTooltip]="'PURCHASES.POST' | translate" />
          }
          @if (b.status === 'posted' || b.status === 'partially_paid') {
            <p-button icon="pi pi-wallet" [rounded]="true" [text]="true" severity="info" (onClick)="openRecordPayment(b)" [pTooltip]="'PURCHASES.RECORD_PAYMENT' | translate" />
          }
          <p-button icon="pi pi-print" [rounded]="true" [text]="true" severity="help" (onClick)="printBill(b)" [pTooltip]="'PURCHASES.PRINT_BILL' | translate" />
          <p-button icon="pi pi-copy" [rounded]="true" [text]="true" severity="secondary" (onClick)="duplicateBill(b)" [pTooltip]="'PURCHASES.DUPLICATE' | translate" />
          @if (b.status !== 'cancelled' && b.status !== 'paid') {
            <p-button icon="pi pi-ban" [rounded]="true" [text]="true" severity="danger" (onClick)="cancelBill(b)" [pTooltip]="'PURCHASES.CANCEL' | translate" />
          }
        </div>
      </td>
    </tr>
  </ng-template>

  <ng-template #filtersTpl>
    <app-sales-filter-bar [statusOptions]="statusOptions" [customers]="filterSuppliers()" (filtersChange)="onFiltersChange($event)" />
  </ng-template>

  <app-data-table
    [data]="tableData()" [lazy]="true" [totalRecords]="totalRecords()" [first]="first" [loading]="tableLoading()" [rows]="rows"
    (onLazyLoad)="onPageChange($event)" [columns]="columns" (retry)="retry()" [bodyTpl]="bodyTpl" [filtersTpl]="filtersTpl"
  />
</div>

<!-- Create/Edit Bill Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingBill() ? ('PURCHASES.EDIT_BILL' | translate) : ('PURCHASES.NEW_BILL' | translate)"
  width="80vw"
  [maximizable]="true"
  [saving]="saving()" [showFooter]="false"
>
  <form [formGroup]="billForm" class="bill-form">
    <!-- Compact header strip: Supplier + Date + Due Date + Warehouse + Settings gear -->
    <div class="form-strip">
      <div class="form-strip-field grow-2">
        <label>{{ 'PURCHASES.SUPPLIER' | translate }} *
          <p-button icon="pi pi-plus" [rounded]="true" [text]="true" size="small" severity="success"
            (onClick)="openQuickAddSupplier()" [pTooltip]="'PURCHASES.ADD_SUPPLIER' | translate" />
        </label>
        <p-select formControlName="supplier_id" [options]="searchedSuppliers()" optionValue="id" [filter]="true" [filterBy]="'name,name_ar,name_en,code'" (onFilter)="onSupplierSearch($event)" (onChange)="onSupplierChange($event.value)" [placeholder]="'PURCHASES.SUPPLIER' | translate" [style]="{ width: '100%' }" appendTo="body" [loading]="supplierSearchLoading()">
          <ng-template #selectedItem let-s><span>{{ s.code }} - {{ s.name }}</span></ng-template>
          <ng-template #item let-s><span>{{ s.code }} - {{ s.name }}</span></ng-template>
        </p-select>
        @if (supplierBalanceLoading()) {
          <div class="supplier-balance-badge loading"><i class="pi pi-spin pi-spinner"></i></div>
        } @else if (supplierBalance() !== null && supplierBalance()! > 0) {
          <div class="supplier-balance-badge danger">
            <i class="pi pi-exclamation-triangle"></i>
            {{ 'PURCHASES.SUPPLIER_BALANCE' | translate }}: {{ supplierBalance() | number:'1.2-2' }}
          </div>
        } @else if (supplierBalance() !== null && supplierBalance()! < 0) {
          <div class="supplier-balance-badge success">
            <i class="pi pi-info-circle"></i>
            {{ 'PURCHASES.SUPPLIER_CREDIT' | translate }}: {{ (supplierBalance()! * -1) | number:'1.2-2' }}
          </div>
        } @else if (supplierBalance() !== null && supplierBalance()! === 0) {
          <div class="supplier-balance-badge success">
            <i class="pi pi-check-circle"></i>
            {{ 'PURCHASES.NO_BALANCE' | translate }}
          </div>
        }
      </div>
      <div class="form-strip-field">
        <label>{{ 'PURCHASES.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="form-strip-field">
        <label>{{ 'PURCHASES.DUE_DATE' | translate }} *</label>
        <p-datepicker formControlName="due_date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      @if (isFieldVisible('warehouse')) {
        <div class="form-strip-field">
          <label>{{ 'PURCHASES.WAREHOUSE' | translate }}</label>
          <p-select
            formControlName="warehouse_id"
            [options]="warehouses()"
            optionLabel="name"
            optionValue="id"
            [filter]="true"
            filterBy="name,name_en,code"
            [showClear]="true"
            [placeholder]="'PURCHASES.WAREHOUSE' | translate"
            [style]="{ width: '100%' }"
            appendTo="body"
            (onChange)="onDefaultWarehouseChange($event.value)"
          >
            <ng-template #item let-wh>
              <span>{{ wh.name }} <small style="color: #94a3b8;">({{ wh.code }})</small></span>
            </ng-template>
            <ng-template #selectedItem let-wh>
              <span>{{ wh.name }}</span>
            </ng-template>
          </p-select>
        </div>
      }
      <!-- Settings gear -->
      <div class="form-strip-field" style="max-width: 32px; align-self: flex-end;">
        <p-button icon="pi pi-cog" [rounded]="true" [text]="true" severity="secondary" size="small"
          (onClick)="fieldSettingsVisible.set(!fieldSettingsVisible())"
          [pTooltip]="'PURCHASES.FIELD_SETTINGS' | translate" />
      </div>
    </div>

    <!-- Secondary strip: Supplier Invoice #, Supplier Invoice Date, Currency, Exchange Rate, Cost Center -->
    @if (isFieldVisible('currency') || isFieldVisible('cost_center')) {
      <div class="form-strip secondary">
        <div class="form-strip-field">
          <label>{{ 'PURCHASES.SUPPLIER_INVOICE_NUMBER' | translate }}</label>
          <input pInputText formControlName="supplier_invoice_number" />
        </div>
        <div class="form-strip-field">
          <label>{{ 'PURCHASES.SUPPLIER_INVOICE_DATE' | translate }}</label>
          <p-datepicker formControlName="supplier_invoice_date" dateFormat="yy-mm-dd" [showIcon]="true" [showClear]="true" />
        </div>
        @if (isFieldVisible('currency')) {
          <div class="form-strip-field" style="max-width: 120px;">
            <label>{{ 'PURCHASES.CURRENCY' | translate }}</label>
            <p-select formControlName="currency_id" [options]="(currencies$ | async) || []" optionLabel="code" optionValue="id" [placeholder]="'PURCHASES.CURRENCY' | translate" [style]="{ width: '100%' }" appendTo="body" [showClear]="true" />
          </div>
          <div class="form-strip-field" style="max-width: 120px;">
            <label>{{ 'PURCHASES.EXCHANGE_RATE' | translate }}</label>
            <p-inputNumber formControlName="exchange_rate" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="6" [style]="{ width: '100%' }" />
          </div>
        }
        @if (isFieldVisible('cost_center')) {
          <div class="form-strip-field">
            <label>{{ 'PURCHASES.COST_CENTER' | translate }}</label>
            <p-select formControlName="cost_center_id" [options]="(costCenters$ | async) || []" optionLabel="name" optionValue="id" [filter]="true" filterBy="name,code" [showClear]="true" [placeholder]="'PURCHASES.COST_CENTER' | translate" [style]="{ width: '100%' }" appendTo="body" />
          </div>
        }
      </div>
    }

    <!-- Field settings panel -->
    @if (fieldSettingsVisible()) {
      <div class="field-settings-panel">
        <div class="field-settings-grid">
          @for (f of [
            {key: 'warehouse', label: 'PURCHASES.SHOW_WAREHOUSE'},
            {key: 'currency', label: 'PURCHASES.SHOW_CURRENCY'},
            {key: 'cost_center', label: 'PURCHASES.SHOW_COST_CENTER'},
            {key: 'tax', label: 'PURCHASES.SHOW_TAX'},
            {key: 'discount', label: 'PURCHASES.SHOW_DISCOUNT'}
          ]; track f.key) {
            <div class="field-toggle-item">
              <p-toggleSwitch [ngModel]="fieldVisibility()[f.key] !== false" [ngModelOptions]="{standalone: true}"
                (ngModelChange)="toggleField(f.key)" />
              <span>{{ f.label | translate }}</span>
            </div>
          }
        </div>
        <p-button icon="pi pi-check" size="small" [label]="'COMMON.SAVE' | translate"
          (onClick)="saveFieldVisibility()" />
      </div>
    }

    <!-- Line Items Section -->
    <div class="lines-section">
      <div class="lines-header">
        <div style="display: flex; align-items: center; gap: 0.5rem;">
          <h3>{{ 'PURCHASES.LINE_ITEMS' | translate }}</h3>
          <p-button icon="pi pi-plus" [label]="'PURCHASES.ADD_LINE' | translate" severity="contrast" [outlined]="true" size="small" (onClick)="addItem()" styleClass="header-add-btn" />
        </div>
        <div class="barcode-row-inline">
          <i class="pi pi-barcode barcode-icon"></i>
          <input pInputText [ngModel]="barcodeValue()" (ngModelChange)="barcodeValue.set($event)" [ngModelOptions]="{standalone: true}" [placeholder]="'INVENTORY.SCAN_BARCODE' | translate" (keydown.enter)="onBarcodeScan($event)" [disabled]="barcodeLoading()" class="barcode-input" />
          @if (barcodeLoading()) { <i class="pi pi-spin pi-spinner" style="color: rgba(255,255,255,0.6);"></i> }
        </div>
      </div>

      <table class="lines-table">
        <thead>
          <tr>
            <th class="col-num">#</th>
            <th class="col-product">{{ 'PURCHASES.PRODUCT' | translate }}</th>
            @if (isFieldVisible('warehouse')) { <th class="col-warehouse">{{ 'PURCHASES.WAREHOUSE' | translate }}</th> }
            <th class="col-unit">{{ 'PURCHASES.UNIT' | translate }}</th>
            <th class="col-qty">{{ 'PURCHASES.QUANTITY' | translate }}</th>
            <th class="col-price">{{ 'PURCHASES.UNIT_COST' | translate }}</th>
            @if (isFieldVisible('discount')) { <th class="col-discount">{{ 'PURCHASES.DISCOUNT' | translate }}</th> }
            @if (isFieldVisible('tax')) { <th class="col-tax">{{ 'PURCHASES.TAX' | translate }}</th> }
            <th class="col-total">{{ 'PURCHASES.LINE_TOTAL' | translate }}</th>
            <th class="col-action"></th>
          </tr>
        </thead>
        <tbody formArrayName="items">
          @for (item of items.controls; track item; let i = $index) {
            <tr [formGroupName]="i">
              <td class="row-num">{{ i + 1 }}</td>
              <td>
                <p-select formControlName="product_id" [options]="searchedProducts()" optionValue="id" [filter]="true" [filterBy]="'name_ar,name_en,code,barcode'" (onFilter)="onProductSearch($event)" (onChange)="onProductSelect(i, $event.value)" appendTo="body" [style]="{ width: '100%' }" [placeholder]="'PURCHASES.PRODUCT' | translate" [loading]="searchLoading()">
                  <ng-template #item let-product>
                    <div style="display: flex; flex-direction: column; gap: 1px;">
                      <small style="color: #94a3b8;">{{ product.category?.name_ar || '\u2014' }}</small>
                      <span>{{ product.name_ar }} <small style="color: #64748b;">({{ product.code }})</small></span>
                      @if (product.barcode) { <small style="color: #94a3b8;"><i class="pi pi-barcode"></i> {{ product.barcode }}</small> }
                    </div>
                  </ng-template>
                  <ng-template #selectedItem let-product><span>{{ product.name_ar }}</span></ng-template>
                </p-select>
                @if (getProductBarcode(item.get('product_id')?.value); as bc) {
                  <div class="row-barcode"><i class="pi pi-barcode"></i> {{ bc }}</div>
                }
              </td>
              @if (isFieldVisible('warehouse')) {
                <td>
                  <p-select formControlName="warehouse_id" [options]="warehouses()" optionLabel="name" optionValue="id" [showClear]="true" [placeholder]="'PURCHASES.WAREHOUSE' | translate" [style]="{ width: '100%' }" appendTo="body" />
                </td>
              }
              <td>
                <p-select formControlName="unit_id" [options]="(units$ | async) || []" optionLabel="name" optionValue="id" [placeholder]="'PURCHASES.UNIT' | translate" [style]="{ width: '100%' }" appendTo="body" />
              </td>
              <td>
                <p-inputNumber formControlName="quantity" [min]="0.01" mode="decimal" [minFractionDigits]="0" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
              </td>
              <td>
                <p-inputNumber formControlName="unit_cost" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
              </td>
              @if (isFieldVisible('discount')) {
                <td>
                  <p-inputNumber formControlName="discount_percent" [min]="0" [max]="100" mode="decimal" [minFractionDigits]="0" [maxFractionDigits]="2" [style]="{ width: '100%' }" suffix="%" />
                </td>
              }
              @if (isFieldVisible('tax')) {
                <td>
                  <p-select formControlName="tax_rate_id" [options]="(taxRates$ | async) || []" optionLabel="name" optionValue="id" [showClear]="true" [placeholder]="'PURCHASES.TAX' | translate" [style]="{ width: '100%' }" appendTo="body" />
                </td>
              }
              <td class="amount line-total-cell">{{ getLineTotal(i) | number:'1.2-2' }}</td>
              <td>
                <p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="danger" (onClick)="removeItem(i)" [disabled]="items.length <= 1" size="small" />
              </td>
            </tr>
          }
        </tbody>
      </table>
      @if (items.length === 0) { <div class="no-items">{{ 'PURCHASES.NO_ITEMS' | translate }}</div> }
    </div>

    <!-- Bottom: Totals + Notes side by side -->
    <div class="bottom-row">
      <div class="notes-compact">
        <div class="form-strip-field grow-2">
          <label>{{ 'PURCHASES.NOTES' | translate }}</label>
          <textarea pTextarea formControlName="notes" rows="1" [autoResize]="true"></textarea>
        </div>
        <div class="form-strip-field grow-2">
          <label>{{ 'PURCHASES.NOTES_AR' | translate }}</label>
          <textarea pTextarea formControlName="notes_ar" rows="1" [autoResize]="true"></textarea>
        </div>
      </div>
      <div class="totals-section">
        <div class="totals-row">
          <span class="totals-label">{{ 'PURCHASES.SUBTOTAL' | translate }}</span>
          <span class="totals-value">{{ subtotal | number:'1.2-2' }}</span>
        </div>
        @if (lineDiscountTotal > 0) {
          <div class="totals-row">
            <span class="totals-label">{{ 'PURCHASES.LINE_DISCOUNTS' | translate }}</span>
            <span class="totals-value discount">- {{ lineDiscountTotal | number:'1.2-2' }}</span>
          </div>
        }
        <!-- Overall bill discount -->
        <div class="totals-row overall-discount-row">
          <span class="totals-label">{{ 'PURCHASES.OVERALL_DISCOUNT' | translate }}</span>
          <div class="overall-discount-input">
            <p-inputNumber
              [ngModel]="overallDiscountValue()"
              (ngModelChange)="overallDiscountValue.set($event)"
              [ngModelOptions]="{standalone: true}"
              [min]="0"
              [max]="overallDiscountType() === 'percent' ? 100 : subtotal"
              mode="decimal"
              [minFractionDigits]="0"
              [maxFractionDigits]="2"
              [style]="{ width: '100px' }"
              inputStyleClass="discount-input-sm"
            />
            <p-button
              [label]="overallDiscountType() === 'percent' ? '%' : getDisplayCurrency()"
              size="small"
              [outlined]="true"
              severity="secondary"
              (onClick)="overallDiscountType.set(overallDiscountType() === 'percent' ? 'amount' : 'percent')"
              [style]="{ 'min-width': '40px' }"
            />
          </div>
        </div>
        @if (overallDiscountComputed > 0) {
          <div class="totals-row">
            <span class="totals-label">{{ 'PURCHASES.AFTER_DISCOUNT' | translate }}</span>
            <span class="totals-value">{{ subtotalAfterDiscount | number:'1.2-2' }}</span>
          </div>
        }
        <div class="totals-row grand-total">
          <span class="totals-label">{{ 'PURCHASES.TOTAL' | translate }}</span>
          <span class="totals-value">{{ total | number:'1.2-2' }}</span>
        </div>
      </div>
    </div>

    <!-- Inline Payment Section -->
    <div class="inline-pay-section">
      <div class="inline-pay-toggle">
        <p-toggleSwitch [ngModel]="inlinePayEnabled()" (ngModelChange)="onInlinePayToggle($event)" [ngModelOptions]="{standalone: true}" />
        <span class="inline-pay-label">{{ 'PURCHASES.PAY_NOW' | translate }}</span>
        @if (inlinePayEnabled()) {
          <div class="inline-pay-quick-btns">
            <p-button [label]="'PURCHASES.PAY_FULL' | translate" size="small" severity="success" [outlined]="true"
              (onClick)="setInlinePayFull()" />
          </div>
        }
      </div>
      @if (inlinePayEnabled()) {
        <div class="inline-pay-fields">
          <div class="inline-pay-field">
            <label>{{ 'PURCHASES.PAY_AMOUNT' | translate }}</label>
            <p-inputNumber [ngModel]="inlinePayAmount()" (ngModelChange)="inlinePayAmount.set($event)"
              [ngModelOptions]="{standalone: true}" [min]="0.01" [max]="total"
              mode="decimal" [minFractionDigits]="2" [style]="{ width: '100%' }" />
          </div>
          <div class="inline-pay-field grow">
            <label>{{ 'PURCHASES.PAY_DESTINATION' | translate }}</label>
            <p-select
              [ngModel]="inlinePayDestId()" (ngModelChange)="inlinePayDestId.set($event)"
              [ngModelOptions]="{standalone: true}"
              [options]="paymentDestinations()"
              optionValue="id"
              [style]="{ width: '100%' }"
              appendTo="body"
            >
              <ng-template #selectedItem let-dest>
                <span><i [class]="dest.icon" style="margin-inline-end: 4px;"></i>{{ dest.label }} <small style="color: #94a3b8;">({{ dest.sublabel }})</small></span>
              </ng-template>
              <ng-template #item let-dest>
                <span><i [class]="dest.icon" style="margin-inline-end: 4px;"></i>{{ dest.label }} <small style="color: #94a3b8;">({{ dest.sublabel }})</small></span>
              </ng-template>
            </p-select>
          </div>
          <div class="inline-pay-field">
            <label>{{ 'PURCHASES.REFERENCE' | translate }}</label>
            <input pInputText [ngModel]="inlinePayReference()" (ngModelChange)="inlinePayReference.set($event)"
              [ngModelOptions]="{standalone: true}" />
          </div>
        </div>
        @if (getInlinePayDest()?.payment_method === 'check') {
          <div class="inline-pay-fields">
            <div class="inline-pay-field">
              <label>{{ 'PURCHASES.CHECK_NUMBER' | translate }}</label>
              <input pInputText [ngModel]="inlinePayCheckNumber()" (ngModelChange)="inlinePayCheckNumber.set($event)"
                [ngModelOptions]="{standalone: true}" />
            </div>
            <div class="inline-pay-field">
              <label>{{ 'PURCHASES.DATE' | translate }}</label>
              <p-datepicker [ngModel]="inlinePayCheckDate()" (ngModelChange)="inlinePayCheckDate.set($event)"
                [ngModelOptions]="{standalone: true}" dateFormat="yy-mm-dd" [showIcon]="true" [style]="{ width: '100%' }" />
            </div>
            <div class="inline-pay-field">
              <label>{{ 'PURCHASES.BANK_ACCOUNT' | translate }}</label>
              <input pInputText [ngModel]="inlinePayCheckBank()" (ngModelChange)="inlinePayCheckBank.set($event)"
                [ngModelOptions]="{standalone: true}" />
            </div>
          </div>
        }
      }
    </div>
  </form>
  <div class="dialog-custom-footer">
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="dialogVisible.set(false)" />
    <p-button
      [label]="inlinePayEnabled() ? ('PURCHASES.PAY_NOW' | translate) : ('COMMON.SAVE' | translate)"
      [icon]="inlinePayEnabled() ? 'pi pi-dollar' : 'pi pi-check'"
      [severity]="inlinePayEnabled() ? 'success' : 'primary'"
      (onClick)="onSave()" [loading]="saving()" [disabled]="items.length < 1" />
    <p-button
      [label]="'PURCHASES.SAVE_AND_PRINT' | translate"
      icon="pi pi-print"
      severity="help"
      (onClick)="onSaveAndPrint()"
      [loading]="saving()"
      [disabled]="items.length < 1"
    />
  </div>
</app-form-dialog>

<!-- View Bill Dialog -->
<p-dialog [header]="'PURCHASES.BILL' | translate" [(visible)]="viewDialogVisible" [modal]="true" [style]="{ width: '950px' }" [closable]="true">
  @if (viewingBill(); as b) {
    <div class="view-bill">
      <div class="view-header-info">
        <div class="info-item"><label>{{ 'PURCHASES.BILL_NUMBER' | translate }}</label><span class="mono">{{ b.bill_number }}</span></div>
        <div class="info-item"><label>{{ 'PURCHASES.DATE' | translate }}</label><span>{{ b.date }}</span></div>
        <div class="info-item"><label>{{ 'PURCHASES.DUE_DATE' | translate }}</label><span>{{ b.due_date }}</span></div>
        <div class="info-item"><label>{{ 'PURCHASES.STATUS' | translate }}</label><p-tag [value]="getStatusLabel(b.status)" [severity]="getStatusSeverity(b.status)" /></div>
        <div class="info-item"><label>{{ 'PURCHASES.SUPPLIER' | translate }}</label><span>{{ b.supplier_name }}</span></div>
        @if (b.supplier_invoice_number) {
          <div class="info-item"><label>{{ 'PURCHASES.SUPPLIER_INVOICE_NUMBER' | translate }}</label><span>{{ b.supplier_invoice_number }}</span></div>
        }
        @if (b.supplier_invoice_date) {
          <div class="info-item"><label>{{ 'PURCHASES.SUPPLIER_INVOICE_DATE' | translate }}</label><span>{{ b.supplier_invoice_date }}</span></div>
        }
      </div>

      <!-- Summary Cards -->
      <div class="summary-cards">
        <div class="summary-card"><span class="card-label">{{ 'PURCHASES.TOTAL' | translate }}</span><span class="card-value">{{ b.total | number:'1.2-2' }}</span></div>
        <div class="summary-card"><span class="card-label">{{ 'PURCHASES.AMOUNT_PAID' | translate }}</span><span class="card-value paid">{{ b.amount_paid | number:'1.2-2' }}</span></div>
        <div class="summary-card"><span class="card-label">{{ 'PURCHASES.BALANCE_DUE' | translate }}</span><span class="card-value balance">{{ b.balance_due | number:'1.2-2' }}</span></div>
      </div>

      @if (b.notes || b.notes_ar) {
        <div class="view-description">
          @if (b.notes) { <label>{{ 'PURCHASES.NOTES' | translate }}</label><p>{{ b.notes }}</p> }
          @if (b.notes_ar) { <label>{{ 'PURCHASES.NOTES_AR' | translate }}</label><p>{{ b.notes_ar }}</p> }
        </div>
      }

      <!-- Items Table -->
      <table class="view-lines-table">
        <thead>
          <tr>
            <th>#</th>
            <th>{{ 'PURCHASES.PRODUCT' | translate }}</th>
            <th>{{ 'PURCHASES.UNIT' | translate }}</th>
            <th>{{ 'PURCHASES.QUANTITY' | translate }}</th>
            <th>{{ 'PURCHASES.UNIT_COST' | translate }}</th>
            <th>{{ 'PURCHASES.DISCOUNT' | translate }}</th>
            <th>{{ 'PURCHASES.TAX' | translate }}</th>
            <th>{{ 'PURCHASES.LINE_TOTAL' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (item of b.items; track $index) {
            <tr>
              <td>{{ $index + 1 }}</td>
              <td>{{ item.product_name }}</td>
              <td>{{ item.unit_name }}</td>
              <td class="amount">{{ item.quantity }}</td>
              <td class="amount">{{ item.unit_cost | number:'1.2-2' }}</td>
              <td class="amount">{{ item.discount_amount | number:'1.2-2' }}</td>
              <td class="amount">{{ item.tax_amount | number:'1.2-2' }}</td>
              <td class="amount">{{ item.line_total | number:'1.2-2' }}</td>
            </tr>
          }
        </tbody>
        <tfoot>
          <tr><td colspan="6"></td><td><strong>{{ 'PURCHASES.SUBTOTAL' | translate }}</strong></td><td class="amount"><strong>{{ b.subtotal | number:'1.2-2' }}</strong></td></tr>
          @if (+b.discount_amount > 0) { <tr><td colspan="6"></td><td>{{ 'PURCHASES.DISCOUNT_AMOUNT' | translate }}</td><td class="amount discount">- {{ b.discount_amount | number:'1.2-2' }}</td></tr> }
          @if (+b.tax_amount > 0) { <tr><td colspan="6"></td><td>{{ 'PURCHASES.TAX_AMOUNT' | translate }}</td><td class="amount">{{ b.tax_amount | number:'1.2-2' }}</td></tr> }
          <tr class="grand-total-row"><td colspan="6"></td><td><strong>{{ 'PURCHASES.TOTAL' | translate }}</strong></td><td class="amount"><strong>{{ b.total | number:'1.2-2' }}</strong></td></tr>
        </tfoot>
      </table>

      <!-- Journal Entry Section -->
      @if (b.journal_entry_id) {
        @if (jeLoading()) {
          <div class="loading-spinner"><i class="pi pi-spin pi-spinner" style="font-size: 2rem;"></i></div>
        } @else if (journalEntry(); as je) {
          <div class="je-section">
            <div class="je-block">
              <div class="je-block-header">
                <i class="pi pi-book"></i>
                <span class="je-block-title">{{ 'PURCHASES.PURCHASE_ENTRY' | translate }}</span>
                <span class="je-number">{{ je.entry_number }}</span>
                <p-tag [value]="je.status" [severity]="je.status === 'posted' ? 'success' : 'warn'" />
              </div>
              @if (je.lines?.length) {
                <table class="je-lines-table">
                  <thead>
                    <tr>
                      <th>{{ 'PURCHASES.JE_ACCOUNT' | translate }}</th>
                      <th class="text-end">{{ 'PURCHASES.JE_DEBIT' | translate }}</th>
                      <th class="text-end">{{ 'PURCHASES.JE_CREDIT' | translate }}</th>
                    </tr>
                  </thead>
                  <tbody>
                    @for (line of je.lines; track line.id) {
                      <tr>
                        <td>{{ line.account?.name || line.account?.code || '\u2014' }}</td>
                        <td class="text-end">{{ line.debit | number:'1.2-2' }}</td>
                        <td class="text-end">{{ line.credit | number:'1.2-2' }}</td>
                      </tr>
                    }
                  </tbody>
                </table>
              }
            </div>
            @if (b.posted_at) {
              <div class="je-meta">
                {{ 'PURCHASES.POSTED_BY' | translate }}: {{ b.posted_by }}
                &mdash; {{ b.posted_at }}
              </div>
            }
          </div>
        }
      }

      <!-- Cancellation Banner -->
      @if (b.status === 'cancelled') {
        <div class="cancellation-banner">
          <i class="pi pi-ban"></i>
          <div class="cancel-info">
            <span class="cancel-title">{{ 'PURCHASES.CANCELLED' | translate }}</span>
            @if (b.cancelled_at) {
              <span class="cancel-meta">{{ b.cancelled_at }}</span>
            }
            @if (b.cancellation_reason) {
              <span class="cancel-reason">{{ b.cancellation_reason }}</span>
            }
          </div>
        </div>
      }

      <!-- Payments Section -->
      @if (billPayments().length > 0) {
        <div class="payments-section">
          <h4>{{ 'PURCHASES.PAYMENTS' | translate }}</h4>
          <table class="view-lines-table">
            <thead>
              <tr>
                <th>{{ 'PURCHASES.PAYMENT_NUMBER' | translate }}</th>
                <th>{{ 'PURCHASES.DATE' | translate }}</th>
                <th>{{ 'PURCHASES.PAYMENT_METHOD' | translate }}</th>
                <th>{{ 'PURCHASES.TOTAL' | translate }}</th>
                <th>{{ 'PURCHASES.STATUS' | translate }}</th>
              </tr>
            </thead>
            <tbody>
              @for (p of billPayments(); track p.id) {
                <tr>
                  <td class="mono">{{ p.payment_number }}</td>
                  <td>{{ p.date }}</td>
                  <td>{{ getPaymentMethodLabel(p.payment_method) }}</td>
                  <td class="amount">{{ p.amount | number:'1.2-2' }}</td>
                  <td><p-tag [value]="getStatusLabel(p.status)" [severity]="getStatusSeverity(p.status)" /></td>
                </tr>
              }
            </tbody>
          </table>
        </div>
      }

      <!-- Action Buttons -->
      @if (b.status === 'approved') {
        <div class="view-actions">
          <p-button [label]="'PURCHASES.POST' | translate" icon="pi pi-upload" severity="success" (onClick)="postBill(b)" />
        </div>
      }
      @if (b.status === 'posted' || b.status === 'partially_paid') {
        <div class="view-actions">
          <p-button [label]="'PURCHASES.RECORD_PAYMENT' | translate" icon="pi pi-wallet" severity="info" (onClick)="openRecordPayment(b)" />
        </div>
      }
      <div class="view-actions">
        <p-button [label]="'PURCHASES.PRINT_BILL' | translate" icon="pi pi-print" severity="info" (onClick)="printBill(b)" />
      </div>
    </div>
  }
  <ng-template #footer>
    <p-button [label]="'COMMON.CLOSE' | translate" icon="pi pi-times" severity="secondary" (onClick)="viewDialogVisible.set(false)" />
  </ng-template>
</p-dialog>

<!-- Record Payment Dialog -->
<p-dialog [header]="'PURCHASES.RECORD_PAYMENT' | translate" [(visible)]="paymentDialogVisible" [modal]="true" [style]="{ width: '550px' }" [closable]="true">
  @if (paymentBill(); as bill) {
    <div class="payment-dialog">
      <div class="payment-summary">
        <div class="pay-info-row">
          <span>{{ 'PURCHASES.BILL_NUMBER' | translate }}</span>
          <span class="mono">{{ bill.bill_number }}</span>
        </div>
        <div class="pay-info-row">
          <span>{{ 'PURCHASES.TOTAL' | translate }}</span>
          <span class="amount">{{ bill.total | number:'1.2-2' }}</span>
        </div>
        <div class="pay-info-row">
          <span>{{ 'PURCHASES.AMOUNT_PAID' | translate }}</span>
          <span class="amount">{{ bill.amount_paid | number:'1.2-2' }}</span>
        </div>
        <div class="pay-info-row">
          <span>{{ 'PURCHASES.BALANCE_DUE' | translate }}</span>
          <span class="amount highlight">{{ bill.balance_due | number:'1.2-2' }}</span>
        </div>
      </div>
      <form [formGroup]="paymentForm" class="payment-form">
        <div class="pay-grid">
          <div class="pay-field">
            <label>{{ 'PURCHASES.PAY_AMOUNT' | translate }} *</label>
            <p-inputNumber formControlName="amount" [min]="0.01" mode="decimal" [minFractionDigits]="2" [style]="{ width: '100%' }" />
          </div>
          <div class="pay-field">
            <label>{{ 'PURCHASES.DATE' | translate }} *</label>
            <p-datepicker formControlName="payment_date" dateFormat="yy-mm-dd" [showIcon]="true" [style]="{ width: '100%' }" />
          </div>
          <div class="pay-field full">
            <label>{{ 'PURCHASES.PAY_DESTINATION' | translate }} *</label>
            <p-select
              [ngModel]="getSelectedDestinationId()"
              [ngModelOptions]="{standalone: true}"
              (ngModelChange)="onDestinationChange($event)"
              [options]="paymentDestinations()"
              optionValue="id"
              [style]="{ width: '100%' }"
              appendTo="body"
            >
              <ng-template #selectedItem let-dest>
                <span><i [class]="dest.icon" style="margin-inline-end: 4px;"></i>{{ dest.label }} <small style="color: #94a3b8;">({{ dest.sublabel }})</small></span>
              </ng-template>
              <ng-template #item let-dest>
                <span><i [class]="dest.icon" style="margin-inline-end: 4px;"></i>{{ dest.label }} <small style="color: #94a3b8;">({{ dest.sublabel }})</small></span>
              </ng-template>
            </p-select>
          </div>
          @if (paymentForm.get('payment_method')?.value === 'check') {
            <div class="pay-field">
              <label>{{ 'PURCHASES.CHECK_NUMBER' | translate }}</label>
              <input pInputText formControlName="check_number" />
            </div>
            <div class="pay-field">
              <label>{{ 'PURCHASES.DATE' | translate }}</label>
              <p-datepicker formControlName="check_date" dateFormat="yy-mm-dd" [showIcon]="true" [style]="{ width: '100%' }" />
            </div>
          }
          <div class="pay-field">
            <label>{{ 'PURCHASES.REFERENCE' | translate }}</label>
            <input pInputText formControlName="reference" />
          </div>
          <div class="pay-field full">
            <label>{{ 'PURCHASES.NOTES' | translate }}</label>
            <textarea pTextarea formControlName="notes" rows="2" style="width: 100%"></textarea>
          </div>
        </div>
      </form>
    </div>
  }
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="paymentDialogVisible.set(false)" />
    <p-button [label]="'COMMON.SAVE' | translate" icon="pi pi-check" (onClick)="savePayment()" [loading]="savingPayment()" />
  </ng-template>
</p-dialog>

<!-- Quick Add Supplier Dialog -->
<p-dialog [header]="'PURCHASES.ADD_SUPPLIER' | translate" [(visible)]="quickAddVisible" [modal]="true" [style]="{ width: '420px' }" [closable]="true">
  <form [formGroup]="quickAddForm" style="display: flex; flex-direction: column; gap: 1rem;">
    <div><label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.NAME_AR' | translate }} *</label><input pInputText formControlName="name_ar" style="width: 100%" /></div>
    <div><label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.NAME_EN' | translate }}</label><input pInputText formControlName="name_en" style="width: 100%" /></div>
    <div><label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.PHONE' | translate }}</label><input pInputText formControlName="phone" style="width: 100%" /></div>
    <div><label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.EMAIL' | translate }}</label><input pInputText formControlName="email" style="width: 100%" type="email" /></div>
  </form>
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="quickAddVisible.set(false)" />
    <p-button [label]="'COMMON.SAVE' | translate" icon="pi pi-check" (onClick)="saveQuickSupplier()" [loading]="quickAddSaving()" />
  </ng-template>
</p-dialog>
