<?php
declare(strict_types=1);

namespace App\Modules\Procurement\Models;

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

class VendorInvoice extends Model
{
    protected static string $table = 'vendor_invoices';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'invoice_number', 'internal_number', 'supplier_id', 'purchase_order_id',
        'grn_id', 'invoice_date', 'due_date', 'subtotal', 'tax_amount',
        'discount_amount', 'total_amount', 'currency', 'status', 'match_status',
        'match_notes', 'journal_entry_id', 'ap_record_id', 'notes', 'branch_id',
    ];

    public static function getStatuses(): array
    {
        return [
            'draft'        => 'مسودة',
            'verified'     => 'تم التحقق',
            'approved'     => 'معتمدة',
            'paid'         => 'مدفوعة',
            'partial_paid' => 'مدفوعة جزئياً',
            'cancelled'    => 'ملغاة',
        ];
    }

    public static function getMatchStatuses(): array
    {
        return [
            'unmatched'      => 'غير مطابق',
            'matched'        => 'مطابق',
            'discrepancy'    => 'يوجد اختلاف',
            'tolerance_pass' => 'مطابق (ضمن التسامح)',
        ];
    }

    public static function getStatusColor(string $status): string
    {
        return match ($status) {
            'draft'        => '#6B7280',
            'verified'     => '#D97706',
            'approved'     => '#0D7377',
            'paid'         => '#059669',
            'partial_paid' => '#2563EB',
            'cancelled'    => '#DC2626',
            default        => '#6B7280',
        };
    }

    public static function getStatusBg(string $status): string
    {
        return match ($status) {
            'draft'        => '#F3F4F6',
            'verified'     => '#FFF7ED',
            'approved'     => '#F0FDFA',
            'paid'         => '#ECFDF5',
            'partial_paid' => '#EFF6FF',
            'cancelled'    => '#FEE2E2',
            default        => '#F3F4F6',
        };
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = 'vi.`is_archived` = 0';
        $params = [];

        if (!empty($filters['status'])) {
            $where .= ' AND vi.`status` = ?';
            $params[] = $filters['status'];
        }
        if (!empty($filters['match_status'])) {
            $where .= ' AND vi.`match_status` = ?';
            $params[] = $filters['match_status'];
        }
        if (!empty($filters['supplier_id'])) {
            $where .= ' AND vi.`supplier_id` = ?';
            $params[] = (int) $filters['supplier_id'];
        }
        if (!empty($filters['date_from'])) {
            $where .= ' AND vi.`invoice_date` >= ?';
            $params[] = $filters['date_from'];
        }
        if (!empty($filters['date_to'])) {
            $where .= ' AND vi.`invoice_date` <= ?';
            $params[] = $filters['date_to'];
        }

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM `vendor_invoices` vi WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT vi.*, s.`name_ar` as supplier_name, po.`po_number`, g.`grn_number`
             FROM `vendor_invoices` vi
             JOIN `suppliers` s ON s.`id` = vi.`supplier_id`
             LEFT JOIN `purchase_orders` po ON po.`id` = vi.`purchase_order_id`
             LEFT JOIN `goods_received_notes` g ON g.`id` = vi.`grn_id`
             WHERE {$where}
             ORDER BY vi.`created_at` DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return ['data' => $rows, 'pagination' => Pagination::paginate($total, $perPage, $page)];
    }
}
