<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'journal_entry_id', 'account_id', 'description', 'debit', 'credit',
        'sort_order', 'created_at',
    ];

    public function getForJournalEntry(int $journalEntryId): array
    {
        return $this->select('journal_entry_lines.*, chart_of_accounts.code as account_code, chart_of_accounts.name as account_name')
            ->join('chart_of_accounts', 'chart_of_accounts.id = journal_entry_lines.account_id', 'left')
            ->where('journal_entry_id', $journalEntryId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('journal_entry_lines.id', 'ASC')
            ->findAll();
    }

    public function replaceForJournalEntry(int $journalEntryId, array $lines): array
    {
        $this->where('journal_entry_id', $journalEntryId)->delete();
        $now = date('Y-m-d H:i:s');
        $sort = 0;
        $totalDebit = 0.0;
        $totalCredit = 0.0;
        $saved = [];

        foreach ($lines as $line) {
            $accountId = (int) ($line['account_id'] ?? 0);
            if ($accountId <= 0) {
                continue;
            }

            $debit  = round((float) ($line['debit'] ?? 0), 2);
            $credit = round((float) ($line['credit'] ?? 0), 2);

            if ($debit <= 0 && $credit <= 0) {
                continue;
            }

            if ($debit > 0 && $credit > 0) {
                $credit = 0.0;
            }

            $totalDebit += $debit;
            $totalCredit += $credit;

            $row = [
                'journal_entry_id' => $journalEntryId,
                'account_id'       => $accountId,
                'description'      => trim((string) ($line['description'] ?? '')) ?: null,
                'debit'            => $debit,
                'credit'           => $credit,
                'sort_order'       => $sort++,
                'created_at'       => $now,
            ];
            $this->insert($row);
            $saved[] = $row;
        }

        return [
            'lines'        => $saved,
            'total_debit'  => round($totalDebit, 2),
            'total_credit' => round($totalCredit, 2),
        ];
    }

    public function countForAccount(int $accountId): int
    {
        return $this->where('account_id', $accountId)->countAllResults();
    }
}
