<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Models;

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

class PurchaseOrder extends Model
{
    protected static string $table = 'purchase_orders';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'po_number',
        'supplier_id',
        'warehouse_id',
        'status',
        'total_amount',
        'tax_amount',
        'grand_total',
        'ordered_by',
        'approved_by',
        'approved_at',
        'expected_delivery_date',
        'received_at',
        'notes',
    ];

    /**
     * Get all PO statuses with Arabic labels.
     */
    public static function getStatuses(): array
    {
        return [
            'draft'              => 'مسودة',
            'submitted'          => 'مُقدّم',
            'approved'           => 'معتمد',
            'partially_received' => 'استلام جزئي',
            'received'           => 'تم الاستلام',
            'cancelled'          => 'ملغي',
        ];
    }

    /**
     * Get the Arabic label for a status.
     */
    public static function getStatusLabel(string $status): string
    {
        $statuses = self::getStatuses();
        return $statuses[$status] ?? $status;
    }

    /**
     * Get the color for a status.
     */
    public static function getStatusColor(string $status): string
    {
        return match ($status) {
            'draft'              => '#6B7280',
            'submitted'          => '#D97706',
            'approved'           => '#0D7377',
            'partially_received' => '#2563EB',
            'received'           => '#059669',
            'cancelled'          => '#DC2626',
            default              => '#6B7280',
        };
    }

    /**
     * Search purchase orders with filters and pagination.
     */
    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 po.`status` = ?';
            $params[] = $filters['status'];
        }

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

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

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

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

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

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

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