<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'run_id', 'fixed_asset_id', 'amount', 'book_value_after', 'created_at',
    ];

    public function getForRun(int $runId): array
    {
        return $this->select('depreciation_run_lines.*, fixed_assets.number as asset_number, fixed_assets.name as asset_name')
            ->join('fixed_assets', 'fixed_assets.id = depreciation_run_lines.fixed_asset_id', 'left')
            ->where('run_id', $runId)
            ->orderBy('depreciation_run_lines.id', 'ASC')
            ->findAll();
    }

    public function replaceForRun(int $runId, array $lines): array
    {
        $this->where('run_id', $runId)->delete();
        $now = date('Y-m-d H:i:s');
        $total = 0.0;
        $saved = [];

        foreach ($lines as $line) {
            $assetId = (int) ($line['fixed_asset_id'] ?? 0);
            $amount  = round((float) ($line['amount'] ?? 0), 2);
            if ($assetId <= 0 || $amount <= 0) {
                continue;
            }

            $total += $amount;
            $row = [
                'run_id'           => $runId,
                'fixed_asset_id'   => $assetId,
                'amount'           => $amount,
                'book_value_after' => round((float) ($line['book_value_after'] ?? 0), 2),
                'created_at'       => $now,
            ];
            $this->insert($row);
            $saved[] = $row;
        }

        return ['lines' => $saved, 'total_amount' => round($total, 2)];
    }

    public function countForAsset(int $assetId): int
    {
        return $this->where('fixed_asset_id', $assetId)->countAllResults();
    }

    public function hasPostedForAsset(int $assetId): bool
    {
        return $this->select('depreciation_run_lines.id')
            ->join('depreciation_runs', 'depreciation_runs.id = depreciation_run_lines.run_id')
            ->where('depreciation_run_lines.fixed_asset_id', $assetId)
            ->where('depreciation_runs.status', 'posted')
            ->countAllResults() > 0;
    }
}
