<?php
declare(strict_types=1);

namespace App\Modules\Sales\Models;

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

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

    protected static array $fillable = [
        'invoice_number',
        'warehouse_id',
        'customer_type',
        'member_id',
        'player_id',
        'guest_name',
        'guest_phone',
        'subtotal',
        'discount_amount',
        'discount_reason',
        'tax_amount',
        'total_amount',
        'amount_paid',
        'amount_refunded',
        'payment_id',
        'payment_method',
        'status',
        'sold_by',
        'sale_date',
        'notes',
    ];

    public static function getStatuses(): array
    {
        return [
            'draft'              => 'مسودة',
            'completed'          => 'مكتمل',
            'partially_refunded' => 'مسترجع جزئيًا',
            'fully_refunded'     => 'مسترجع بالكامل',
            'voided'             => 'ملغي',
        ];
    }

    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',
            'completed'          => '#059669',
            'partially_refunded' => '#D97706',
            'fully_refunded'     => '#DC2626',
            'voided'             => '#DC2626',
            default              => '#6B7280',
        };
    }

    public static function getCustomerTypes(): array
    {
        return [
            'member' => 'عضو',
            'player' => 'لاعب',
            'guest'  => 'زائر',
        ];
    }

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

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $where .= ' AND (s.`invoice_number` LIKE ? OR s.`guest_name` LIKE ?)';
            $params[] = $search;
            $params[] = $search;
        }

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

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

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

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

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

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

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

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