<?php

namespace App\Models;

use CodeIgniter\Model;

class BankReconciliationLineModel extends Model
{
    protected $table         = 'bank_reconciliation_lines';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = [
        'reconciliation_id', 'journal_entry_line_id', 'txn_date',
        'description', 'amount', 'is_cleared', 'created_at',
    ];

    public function getForReconciliation(int $reconciliationId): array
    {
        return $this->where('reconciliation_id', $reconciliationId)
            ->orderBy('txn_date', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function replaceForReconciliation(int $reconciliationId, array $lines): void
    {
        $this->where('reconciliation_id', $reconciliationId)->delete();
        $now = date('Y-m-d H:i:s');

        foreach ($lines as $line) {
            $this->insert([
                'reconciliation_id'     => $reconciliationId,
                'journal_entry_line_id' => ! empty($line['journal_entry_line_id']) ? (int) $line['journal_entry_line_id'] : null,
                'txn_date'              => $line['txn_date'] ?? null,
                'description'           => trim((string) ($line['description'] ?? '')) ?: null,
                'amount'                => round((float) ($line['amount'] ?? 0), 2),
                'is_cleared'            => ! empty($line['is_cleared']) ? 1 : 0,
                'created_at'            => $now,
            ]);
        }
    }
}
