<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

use App\Core\Model;
use App\Core\App;

class InstrumentPortfolio extends Model
{
    protected static string $table = 'instrument_portfolios';
    protected static array $fillable = [
        'portfolio_number', 'portfolio_type', 'portfolio_date',
        'bank_account_id', 'total_amount', 'instrument_count',
        'description', 'branch_id', 'journal_entry_id', 'status', 'created_by',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;

    public static array $typeLabels = [
        'deposit'     => 'حافظة إيداع',
        'collection'  => 'حافظة تحصيل',
        'payment'     => 'حافظة دفع',
        'endorsement' => 'حافظة تظهير',
        'return'      => 'حافظة مرتجعات',
        'bounce'      => 'حافظة مرتدات',
    ];

    public static function generateNumber(string $type): string
    {
        $db = App::getInstance()->db();
        $prefix = strtoupper(substr($type, 0, 3)) . '-' . date('Y');
        $last = $db->selectOne(
            "SELECT portfolio_number FROM instrument_portfolios WHERE portfolio_number LIKE ? ORDER BY id DESC LIMIT 1",
            [$prefix . '%']
        );

        if ($last) {
            $num = (int)substr($last['portfolio_number'], -4) + 1;
        } else {
            $num = 1;
        }

        return $prefix . '-' . str_pad((string)$num, 4, '0', STR_PAD_LEFT);
    }

    public function getItems(): array
    {
        $db = App::getInstance()->db();
        return $db->select("
            SELECT ni.*
            FROM negotiable_instruments ni
            JOIN instrument_portfolio_items ipi ON ipi.instrument_id = ni.id
            WHERE ipi.portfolio_id = ?
            ORDER BY ni.due_date ASC
        ", [(int)$this->id]);
    }

    public function addItem(int $instrumentId): void
    {
        $db = App::getInstance()->db();
        $db->insert('instrument_portfolio_items', [
            'portfolio_id'  => (int)$this->id,
            'instrument_id' => $instrumentId,
        ]);
        $this->recalculate();
    }

    public function recalculate(): void
    {
        $db = App::getInstance()->db();
        $stats = $db->selectOne("
            SELECT COUNT(*) as cnt, COALESCE(SUM(ni.amount), 0) as total
            FROM negotiable_instruments ni
            JOIN instrument_portfolio_items ipi ON ipi.instrument_id = ni.id
            WHERE ipi.portfolio_id = ?
        ", [(int)$this->id]);

        $this->update([
            'instrument_count' => (int)$stats['cnt'],
            'total_amount'     => (float)$stats['total'],
        ]);
    }
}
