<?php
declare(strict_types=1);

namespace App\Modules\Procurement\Models;

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

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

    protected static array $fillable = [
        'grn_number',
        'purchase_order_id',
        'supplier_id',
        'warehouse_id',
        'received_by',
        'received_date',
        'status',
        'total_received_value',
        'total_accepted_value',
        'inspection_notes',
        'notes',
        'branch_id',
    ];

    public static function getStatuses(): array
    {
        return [
            'draft'          => 'مسودة',
            'inspecting'     => 'تحت الفحص',
            'accepted'       => 'مقبول',
            'partial_accept' => 'قبول جزئي',
            'cancelled'      => 'ملغي',
        ];
    }

    public static function getStatusColor(string $status): string
    {
        return match ($status) {
            'draft'          => '#6B7280',
            'inspecting'     => '#D97706',
            'accepted'       => '#059669',
            'partial_accept' => '#2563EB',
            'cancelled'      => '#DC2626',
            default          => '#6B7280',
        };
    }

    public static function getStatusBg(string $status): string
    {
        return match ($status) {
            'draft'          => '#F3F4F6',
            'inspecting'     => '#FFF7ED',
            'accepted'       => '#ECFDF5',
            'partial_accept' => '#EFF6FF',
            'cancelled'      => '#FEE2E2',
            default          => '#F3F4F6',
        };
    }

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

        if (!empty($filters['status'])) {
            $where .= ' AND g.`status` = ?';
            $params[] = $filters['status'];
        }

        if (!empty($filters['supplier_id'])) {
            $where .= ' AND g.`supplier_id` = ?';
            $params[] = (int) $filters['supplier_id'];
        }

        if (!empty($filters['warehouse_id'])) {
            $where .= ' AND g.`warehouse_id` = ?';
            $params[] = (int) $filters['warehouse_id'];
        }

        if (!empty($filters['date_from'])) {
            $where .= ' AND g.`received_date` >= ?';
            $params[] = $filters['date_from'];
        }

        if (!empty($filters['date_to'])) {
            $where .= ' AND g.`received_date` <= ?';
            $params[] = $filters['date_to'];
        }

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

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

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

    public static function getForPO(int $poId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT g.*, s.`name_ar` as supplier_name, w.`name_ar` as warehouse_name
             FROM `goods_received_notes` g
             JOIN `suppliers` s ON s.`id` = g.`supplier_id`
             JOIN `warehouses` w ON w.`id` = g.`warehouse_id`
             WHERE g.`purchase_order_id` = ? AND g.`is_archived` = 0
             ORDER BY g.`created_at` DESC",
            [$poId]
        );
    }
}
