<?php
declare(strict_types=1);

namespace App\Modules\PlaygroundAdmin\Controllers;

use App\Core\Controller;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Modules\PlaygroundAdmin\Models\PlaygroundConfiguration;

final class PlaygroundController extends Controller
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    public function index(Request $request): Response
    {
        $this->authorize('playground.view');

        $filters = ['type' => $request->get('type'), 'is_active' => $request->get('is_active')];
        $page = max(1, (int) ($request->get('page') ?? 1));
        $result = PlaygroundConfiguration::search(array_filter($filters), 25, $page);

        return $this->view('PlaygroundAdmin.Views.index', [
            'playgrounds' => $result['data'],
            'pagination' => $result['pagination'],
            'filters' => $filters,
            'types' => PlaygroundConfiguration::getTypes(),
        ]);
    }

    public function create(Request $request): Response
    {
        $this->authorize('playground.manage');
        $db = App::getInstance()->db();

        $facilities = $db->select("SELECT id, name_ar FROM facilities WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar");

        return $this->view('PlaygroundAdmin.Views.create', [
            'types' => PlaygroundConfiguration::getTypes(),
            'facilities' => $facilities,
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('playground.manage');
        $data = $request->all();
        $session = App::getInstance()->session();

        $errors = [];
        if (empty($data['playground_name_ar'])) $errors[] = 'اسم الملعب مطلوب';
        if (empty($data['playground_type'])) $errors[] = 'نوع الملعب مطلوب';
        if (empty($data['facility_id'])) $errors[] = 'المرفق مطلوب';

        if (!empty($errors)) {
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            $session->flash('_old_input', $data);
            return $this->redirect('/playgrounds/create');
        }

        $employee = App::getInstance()->currentEmployee();
        $hasRows = in_array($data['playground_type'], PlaygroundConfiguration::getRowTypes());

        $db = App::getInstance()->db();
        $db->insert('playground_configurations', [
            'facility_id' => (int) $data['facility_id'],
            'playground_name_ar' => $data['playground_name_ar'],
            'playground_type' => $data['playground_type'],
            'has_rows' => $hasRows ? 1 : 0,
            'row_count' => $hasRows ? ((int) ($data['row_count'] ?? 0) ?: null) : null,
            'row_label_ar' => $data['row_label_ar'] ?? 'حارة',
            'operating_hours_json' => !empty($data['operating_hours']) ? json_encode($data['operating_hours']) : null,
            'notes' => $data['notes'] ?? null,
            'created_by' => $employee ? (int) $employee->id : null,
        ]);

        $id = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id")['id'];

        return $this->redirect('/playgrounds/' . $id)->withSuccess('تم إنشاء الملعب بنجاح');
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('playground.view');
        $db = App::getInstance()->db();

        $playground = $db->selectOne(
            "SELECT pc.*, f.name_ar as facility_name
             FROM playground_configurations pc
             LEFT JOIN facilities f ON f.id = pc.facility_id
             WHERE pc.id = ?",
            [(int) $id]
        );

        if (!$playground) {
            return $this->redirect('/playgrounds')->withError('الملعب غير موجود');
        }

        return $this->view('PlaygroundAdmin.Views.show', [
            'playground' => $playground,
            'types' => PlaygroundConfiguration::getTypes(),
        ]);
    }

    public function edit(Request $request, string $id): Response
    {
        $this->authorize('playground.manage');
        $db = App::getInstance()->db();

        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);
        if (!$playground) {
            return $this->redirect('/playgrounds')->withError('الملعب غير موجود');
        }

        $facilities = $db->select("SELECT id, name_ar FROM facilities WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar");

        return $this->view('PlaygroundAdmin.Views.edit', [
            'playground' => $playground,
            'types' => PlaygroundConfiguration::getTypes(),
            'facilities' => $facilities,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $this->authorize('playground.manage');
        $data = $request->all();
        $db = App::getInstance()->db();

        $hasRows = in_array($data['playground_type'] ?? '', PlaygroundConfiguration::getRowTypes());

        $db->update('playground_configurations', [
            'playground_name_ar' => $data['playground_name_ar'] ?? '',
            'playground_type' => $data['playground_type'] ?? '',
            'facility_id' => (int) ($data['facility_id'] ?? 0),
            'has_rows' => $hasRows ? 1 : 0,
            'row_count' => $hasRows ? ((int) ($data['row_count'] ?? 0) ?: null) : null,
            'row_label_ar' => $data['row_label_ar'] ?? 'حارة',
            'notes' => $data['notes'] ?? null,
            'updated_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $id]);

        return $this->redirect('/playgrounds/' . $id)->withSuccess('تم تحديث الملعب بنجاح');
    }

    public function toggle(Request $request, string $id): Response
    {
        $this->authorize('playground.manage');
        $db = App::getInstance()->db();

        $playground = $db->selectOne("SELECT is_active FROM playground_configurations WHERE id = ?", [(int) $id]);
        if (!$playground) {
            return $this->redirect('/playgrounds')->withError('الملعب غير موجود');
        }

        $db->update('playground_configurations', [
            'is_active' => $playground['is_active'] ? 0 : 1,
            'updated_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $id]);

        return $this->redirect('/playgrounds/' . $id)->withSuccess('تم تحديث حالة الملعب');
    }
}
