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

<div class="payments-page">
  <app-page-header title="PURCHASES.PAYMENTS" subtitle="PURCHASES.TITLE" (refresh)="retry()">
    <p-button
      [label]="'PURCHASES.SETTLE_BILLS' | translate"
      icon="pi pi-wallet"
      (onClick)="openSettleDialog()"
    />
  </app-page-header>

  <ng-template #bodyTpl let-pay>
    <tr>
      <td class="mono">{{ pay.payment_number }}</td>
      <td>{{ pay.date }}</td>
      <td class="mono">{{ pay.bill?.bill_number || '-' }}</td>
      <td>{{ pay.partner?.name || '-' }}</td>
      <td class="amount">{{ pay.amount | number:'1.2-2' }}</td>
      <td>{{ getPaymentMethodLabel(pay.payment_method) }}</td>
      <td><p-tag [value]="getStatusLabel(pay.status)" [severity]="getStatusSeverity(pay.status)" /></td>
      <td>
        <div class="action-buttons">
          <p-button icon="pi pi-eye" [rounded]="true" [text]="true" severity="info" (onClick)="viewPayment(pay)" [pTooltip]="'COMMON.VIEW' | translate" />
          @if (pay.status === 'draft') {
            <p-button icon="pi pi-check-circle" [rounded]="true" [text]="true" severity="success" (onClick)="postPayment(pay)" [pTooltip]="'PURCHASES.POST' | translate" />
            <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" (onClick)="deletePayment(pay)" [pTooltip]="'COMMON.DELETE' | translate" />
          }
          @if (pay.status !== 'cancelled') {
            <p-button icon="pi pi-ban" [rounded]="true" [text]="true" severity="danger" (onClick)="cancelPayment(pay)" [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>

<!-- View Payment Dialog -->
<p-dialog [header]="'PURCHASES.PAYMENT' | translate" [(visible)]="viewDialogVisible" [modal]="true" [style]="{ width: '650px' }" [closable]="true">
  @if (viewingPayment(); as pay) {
    <div class="view-payment">
      <div class="view-header-info">
        <div class="info-item"><label>{{ 'PURCHASES.PAYMENT_NUMBER' | translate }}</label><span class="mono">{{ pay.payment_number }}</span></div>
        <div class="info-item"><label>{{ 'PURCHASES.DATE' | translate }}</label><span>{{ pay.date }}</span></div>
        <div class="info-item"><label>{{ 'PURCHASES.STATUS' | translate }}</label><p-tag [value]="getStatusLabel(pay.status)" [severity]="getStatusSeverity(pay.status)" /></div>
        <div class="info-item"><label>{{ 'PURCHASES.AMOUNT' | translate }}</label><span class="amount-big">{{ pay.amount | number:'1.2-2' }}</span></div>
        <div class="info-item"><label>{{ 'PURCHASES.PAYMENT_METHOD' | translate }}</label><span>{{ getPaymentMethodLabel(pay.payment_method) }}</span></div>
        @if (pay.bill) { <div class="info-item"><label>{{ 'PURCHASES.BILL' | translate }}</label><span class="mono">{{ pay.bill.bill_number }}</span></div> }
        @if (pay.partner) { <div class="info-item"><label>{{ 'PURCHASES.SUPPLIER' | translate }}</label><span>{{ pay.partner.name }}</span></div> }
        @if (pay.bank_account) { <div class="info-item"><label>{{ 'PURCHASES.BANK_ACCOUNT' | translate }}</label><span>{{ pay.bank_account.bank_name }} - {{ pay.bank_account.account_number }}</span></div> }
        @if (pay.paying_account) { <div class="info-item"><label>{{ 'PURCHASES.PAYING_ACCOUNT' | translate }}</label><span>{{ pay.paying_account.code }} - {{ pay.paying_account.name }}</span></div> }
        @if (pay.check_number) { <div class="info-item"><label>{{ 'PURCHASES.CHECK_NUMBER' | translate }}</label><span class="mono">{{ pay.check_number }}</span></div> }
        @if (pay.reference) { <div class="info-item"><label>{{ 'PURCHASES.REFERENCE' | translate }}</label><span>{{ pay.reference }}</span></div> }
        @if (pay.journal_entry) { <div class="info-item"><label>{{ 'PURCHASES.JOURNAL_ENTRY' | translate }}</label><span class="mono">#{{ pay.journal_entry.id }} - {{ pay.journal_entry.entry_number }}</span></div> }
      </div>
      @if (pay.notes) {
        <div class="view-notes">
          <label>{{ 'PURCHASES.NOTES' | translate }}</label>
          <p>{{ pay.notes }}</p>
        </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>

<!-- Settlement Dialog -->
<p-dialog
  [header]="'PURCHASES.SETTLE_BILLS' | translate"
  [(visible)]="settleDialogVisible"
  [modal]="true"
  [style]="{ width: '850px' }"
  [closable]="true"
>
  <div class="settle-form">
    <div class="settle-grid">
      <div class="settle-field">
        <label>{{ 'PURCHASES.SUPPLIER' | translate }} *</label>
        <p-select
          [ngModel]="settleSupplierId()"
          (ngModelChange)="onSettleSupplierChange($event)"
          [options]="suppliers()"
          optionLabel="name"
          optionValue="id"
          [filter]="true"
          filterBy="name,code"
          [placeholder]="'COMMON.SELECT' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
        />
        @if (partnerBalance() !== null) {
          <span class="partner-balance" [class.credit]="partnerBalance()! < 0">
            {{ 'COMMON.BALANCE' | translate }}: {{ partnerBalance()! | number:'1.2-2' }}
            @if (partnerBalance()! < 0) { ({{ 'PURCHASES.CREDIT_BALANCE' | translate }}) }
          </span>
        }
        @if (partnerBalanceLoading()) {
          <span class="partner-balance">...</span>
        }
      </div>
      <div class="settle-field">
        <label>{{ 'PURCHASES.DATE' | translate }} *</label>
        <p-datepicker [(ngModel)]="settleDate" dateFormat="yy-mm-dd" [style]="{ width: '100%' }" appendTo="body" />
      </div>
      @if (partnerBalance() !== null && (partnerBalance()! - totalOutstanding()) < 0 && outstandingBills().length > 0) {
        <div class="settle-field settle-from-balance-field">
          <label>
            <input type="checkbox" [checked]="settleFromBalance()" (change)="toggleSettleFromBalance($any($event.target).checked)" />
            {{ 'PURCHASES.SETTLE_FROM_BALANCE' | translate }}
          </label>
          <span class="balance-hint">{{ 'PURCHASES.SETTLE_FROM_BALANCE_HINT' | translate:{ amount: ((partnerBalance()! * -1 + totalOutstanding()) | number:'1.2-2') } }}</span>
        </div>
      }
      @if (!settleFromBalance()) {
        <div class="settle-field">
          <label>{{ 'PURCHASES.AMOUNT' | translate }} *</label>
          <p-inputNumber
            [ngModel]="settleAmount()"
            (ngModelChange)="onSettleAmountChange($event)"
            [minFractionDigits]="2"
            [min]="0.01"
            [style]="{ width: '100%' }"
          />
        </div>
        <div class="settle-field">
          <label>{{ 'PURCHASES.PAYMENT_METHOD' | translate }}</label>
          <p-select
            [ngModel]="settlePaymentMethod()"
            (ngModelChange)="onSettleMethodChange($event)"
            [options]="paymentMethods"
            optionLabel="label"
            optionValue="value"
            [style]="{ width: '100%' }"
            appendTo="body"
          >
            <ng-template #selectedItem let-item>
              <span>{{ item.label | translate }}</span>
            </ng-template>
            <ng-template #item let-item>
              <span>{{ item.label | translate }}</span>
            </ng-template>
          </p-select>
        </div>
        <div class="settle-field">
          <label>{{ 'PURCHASES.PAYING_ACCOUNT' | translate }} *</label>
          <p-select
            [ngModel]="settleAccountId()"
            (ngModelChange)="onSettleAccountChange($event)"
            [options]="paymentAccountOptions()"
            optionLabel="label"
            optionValue="value"
            [placeholder]="'COMMON.SELECT' | translate"
            [style]="{ width: '100%' }"
            appendTo="body"
          />
        </div>
      }
      <div class="settle-field">
        <label>{{ 'PURCHASES.NOTES' | translate }}</label>
        <input pInputText [ngModel]="settleNotes()" (ngModelChange)="settleNotes.set($event)" style="width: 100%" />
      </div>
    </div>

    @if (settleLoading()) {
      <div class="settle-loading">
        <p-progressSpinner strokeWidth="3" [style]="{ width: '40px', height: '40px' }" />
      </div>
    } @else if (outstandingBills().length > 0) {
      <div class="settle-summary">
        <div class="summary-item">
          <span class="summary-label">{{ 'PURCHASES.TOTAL_OUTSTANDING' | translate }}</span>
          <span class="summary-value outstanding">{{ totalOutstanding() | number:'1.2-2' }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">{{ 'PURCHASES.TOTAL_ALLOCATED' | translate }}</span>
          <span class="summary-value allocated">{{ totalAllocated() | number:'1.2-2' }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">{{ 'PURCHASES.REMAINING' | translate }}</span>
          <span class="summary-value" [class.over]="remainingAmount() < 0" [class.allocated]="remainingAmount() > 0">{{ remainingAmount() | number:'1.2-2' }}</span>
          @if (remainingAmount() > 0) {
            <span class="summary-hint">{{ 'PURCHASES.EXCESS_TO_BALANCE' | translate }}</span>
          }
        </div>
      </div>

      <table class="settle-table">
        <thead>
          <tr>
            <th>{{ 'PURCHASES.BILL_NUMBER' | translate }}</th>
            <th>{{ 'PURCHASES.DATE' | translate }}</th>
            <th>{{ 'PURCHASES.DUE_DATE' | translate }}</th>
            <th class="text-end">{{ 'PURCHASES.TOTAL' | translate }}</th>
            <th class="text-end">{{ 'PURCHASES.PAID' | translate }}</th>
            <th class="text-end">{{ 'PURCHASES.BALANCE_DUE' | translate }}</th>
            <th class="text-end">{{ 'PURCHASES.ALLOCATED_AMOUNT' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (bill of outstandingBills(); track bill.id; let i = $index) {
            <tr [class.fully-allocated]="bill.allocated >= bill.balance_due">
              <td class="mono">{{ bill.bill_number }}</td>
              <td>{{ bill.date }}</td>
              <td>{{ bill.due_date }}</td>
              <td class="text-end">{{ bill.total | number:'1.2-2' }}</td>
              <td class="text-end">{{ bill.amount_paid | number:'1.2-2' }}</td>
              <td class="text-end fw-600">{{ bill.balance_due | number:'1.2-2' }}</td>
              <td class="text-end">
                <p-inputNumber
                  [ngModel]="bill.allocated"
                  (ngModelChange)="onAllocationChange(i, $event)"
                  [minFractionDigits]="2"
                  [min]="0"
                  [max]="bill.balance_due"
                  [style]="{ width: '120px' }"
                  inputStyleClass="text-end"
                />
              </td>
            </tr>
          }
        </tbody>
      </table>
    } @else if (settleSupplierId()) {
      <div class="settle-empty">
        <i class="pi pi-check-circle"></i>
        <p>{{ 'PURCHASES.NO_OUTSTANDING_BILLS' | translate }}</p>
      </div>
    }
  </div>

  <ng-template #footer>
    <div class="settle-footer">
      <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="settleDialogVisible.set(false)" />
      <p-button
        [label]="'PURCHASES.SETTLE_AND_POST' | translate"
        icon="pi pi-check"
        (onClick)="saveSettlement()"
        [loading]="settleSaving()"
        [disabled]="totalAllocated() <= 0 || (settleFromBalance() ? !selectedPartnerApAccountId() : !settleAccountId())"
      />
    </div>
  </ng-template>
</p-dialog>
