<?php
declare(strict_types=1);

namespace App\Modules\Procurement\Models;

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

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

    protected static array $fillable = [
        'rtv_number', 'supplier_id', 'grn_id', 'purchase_order_id', 'warehouse_id',
        'reason', 'return_date', 'status', 'total_amount', 'debit_note_number',
        'debit_note_amount', 'debit_note_date', 'journal_entry_id',
        'approved_by', 'approved_at', 'shipped_by', 'shipped_at',
        'completed_by', 'completed_at', 'notes', 'branch_id',
    ];

    public static function getStatuses(): array
    {
        return [
            'draft'     => 'مسودة',
            'submitted' => 'مُقدّم',
            'approved'  => 'معتمد',
            'shipped'   => 'تم الشحن',
            'completed' => 'مكتمل',
            'cancelled' => 'ملغي',
        ];
    }

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

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

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

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

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

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

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