<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Models;

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

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

    protected static array $fillable = [
        'audit_number',
        'warehouse_id',
        'audit_type',
        'category_id',
        'status',
        'audit_date',
        'started_at',
        'completed_at',
        'approved_by',
        'approved_at',
        'total_items',
        'items_counted',
        'variance_count',
        'notes',
    ];

    public static function getAuditTypes(): array
    {
        return [
            'full'       => 'جرد شامل',
            'partial'    => 'جرد جزئي',
            'spot_check' => 'جرد عشوائي',
        ];
    }

    public static function getStatuses(): array
    {
        return [
            'draft'            => 'مسودة',
            'in_progress'      => 'جارٍ',
            'pending_approval' => 'في انتظار الاعتماد',
            'approved'         => 'معتمد',
            'cancelled'        => 'ملغي',
        ];
    }

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

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

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

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

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

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

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

        $rows = $db->select(
            "SELECT a.*, w.`name_ar` as warehouse_name
             FROM `stock_audits` a
             JOIN `warehouses` w ON w.`id` = a.`warehouse_id`
             WHERE {$where}
             ORDER BY a.`created_at` DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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