<?php
declare(strict_types=1);

namespace App\Modules\Procurement\Models;

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

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

    protected static array $fillable = [
        'pr_number',
        'requested_by',
        'department',
        'status',
        'urgency',
        'required_date',
        'justification',
        'estimated_total',
        'approved_by',
        'approved_at',
        'rejected_by',
        'rejected_at',
        'rejection_reason',
        'converted_po_id',
        'notes',
        'branch_id',
    ];

    public static function getStatuses(): array
    {
        return [
            'draft'     => 'مسودة',
            'submitted' => 'مُقدّم',
            'approved'  => 'معتمد',
            'rejected'  => 'مرفوض',
            'converted' => 'تم التحويل',
            'cancelled' => 'ملغي',
        ];
    }

    public static function getStatusLabel(string $status): string
    {
        return self::getStatuses()[$status] ?? $status;
    }

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

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

    public static function getUrgencyLevels(): array
    {
        return [
            'low'      => 'منخفض',
            'normal'   => 'عادي',
            'high'     => 'عاجل',
            'critical' => 'حرج',
        ];
    }

    public static function getUrgencyColor(string $urgency): string
    {
        return match ($urgency) {
            'low'      => '#6B7280',
            'normal'   => '#2563EB',
            'high'     => '#D97706',
            'critical' => '#DC2626',
            default    => '#6B7280',
        };
    }

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

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

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

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

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

        if (!empty($filters['date_to'])) {
            $where .= ' AND pr.`created_at` <= ?';
            $params[] = $filters['date_to'] . ' 23:59:59';
        }

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

        $rows = $db->select(
            "SELECT pr.*, e.`full_name_ar` as requester_name
             FROM `purchase_requisitions` pr
             LEFT JOIN `employees` e ON e.`id` = pr.`requested_by`
             WHERE {$where}
             ORDER BY pr.`created_at` DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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