<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

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

class AccountReceivable extends Model
{
    protected static string $table = 'accounts_receivable';
    protected static array $fillable = [
        'member_id', 'document_type', 'document_id', 'document_number',
        'document_date', 'due_date', 'description_ar', 'description_en',
        'total_amount', 'paid_amount', 'balance', 'currency', 'status',
        'journal_entry_id', 'payment_entry_id', 'cost_center_id', 'branch_id', 'notes',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;

    public static function getOutstanding(?int $memberId = null): array
    {
        $db = App::getInstance()->db();
        $where = "ar.is_archived = 0 AND ar.status IN ('pending','partial','overdue')";
        $params = [];

        if ($memberId !== null) {
            $where .= ' AND ar.member_id = ?';
            $params[] = $memberId;
        }

        return $db->select(
            "SELECT ar.*, m.full_name_ar as member_name, m.form_number
             FROM accounts_receivable ar
             LEFT JOIN members m ON m.id = ar.member_id
             WHERE {$where}
             ORDER BY ar.due_date ASC",
            $params
        );
    }

    public static function getAgingSummary(): array
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');
        return $db->selectOne(
            "SELECT
                SUM(CASE WHEN due_date >= ? THEN balance ELSE 0 END) as current_amount,
                SUM(CASE WHEN due_date < ? AND due_date >= DATE_SUB(?, INTERVAL 30 DAY) THEN balance ELSE 0 END) as days_30,
                SUM(CASE WHEN due_date < DATE_SUB(?, INTERVAL 30 DAY) AND due_date >= DATE_SUB(?, INTERVAL 60 DAY) THEN balance ELSE 0 END) as days_60,
                SUM(CASE WHEN due_date < DATE_SUB(?, INTERVAL 60 DAY) AND due_date >= DATE_SUB(?, INTERVAL 90 DAY) THEN balance ELSE 0 END) as days_90,
                SUM(CASE WHEN due_date < DATE_SUB(?, INTERVAL 90 DAY) THEN balance ELSE 0 END) as over_90,
                SUM(balance) as total
             FROM accounts_receivable
             WHERE is_archived = 0 AND status IN ('pending','partial','overdue')",
            [$today, $today, $today, $today, $today, $today, $today, $today]
        );
    }

    public static function findByDocument(string $type, int $documentId): ?static
    {
        $row = static::query()
            ->where('document_type', '=', $type)
            ->where('document_id', '=', $documentId)
            ->where('is_archived', '=', 0)
            ->first();
        if ($row === null) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }
}
