<?php
declare(strict_types=1);

namespace App\Modules\PlaygroundAdmin\Models;

use App\Core\Model;

final class PlaygroundConfiguration extends Model
{
    protected string $table = 'playground_configurations';
    protected bool $timestamps = true;

    protected array $fillable = [
        'facility_id', 'playground_name_ar', 'playground_type', 'has_rows',
        'row_count', 'row_label_ar', 'grid_id', 'operating_hours_json',
        'notes', 'is_active', 'created_by',
    ];

    public static function getTypes(): array
    {
        return [
            'football' => 'كرة قدم',
            'tennis' => 'تنس',
            'bowling' => 'بولينج',
            'playstation' => 'بلاي ستيشن',
            'swimming' => 'سباحة',
            'basketball' => 'كرة سلة',
            'paddle' => 'بادل',
            'gym' => 'جيم',
            'ping_pong' => 'تنس طاولة',
        ];
    }

    public static function getRowTypes(): array
    {
        return ['bowling', 'swimming'];
    }

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

        if (!empty($filters['type'])) {
            $where[] = 'pc.playground_type = ?';
            $params[] = $filters['type'];
        }
        if (isset($filters['is_active'])) {
            $where[] = 'pc.is_active = ?';
            $params[] = (int) $filters['is_active'];
        }

        $whereClause = implode(' AND ', $where);

        $total = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM playground_configurations pc WHERE {$whereClause}",
            $params
        )['cnt'] ?? 0);

        $lastPage = max(1, (int) ceil($total / $perPage));
        $page = min($page, $lastPage);
        $offset = ($page - 1) * $perPage;

        $data = $db->select(
            "SELECT pc.*, f.name_ar as facility_name, f.facility_type
             FROM playground_configurations pc
             LEFT JOIN facilities f ON f.id = pc.facility_id
             WHERE {$whereClause}
             ORDER BY pc.playground_name_ar
             LIMIT ? OFFSET ?",
            array_merge($params, [$perPage, $offset])
        );

        return [
            'data' => $data,
            'pagination' => ['total' => $total, 'per_page' => $perPage, 'current_page' => $page, 'last_page' => $lastPage],
        ];
    }
}
