<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\SportsActivity\Services\PlayerLifecycleService;

class PlayerLifecycleController extends Controller
{
    public function pause(Request $request, string $pid, string $gid): Response
    {
        $month = trim((string) $request->post('month', ''));
        $reason = trim((string) $request->post('reason', ''));

        if ($month === '') {
            return $this->redirect("/sa/players/{$pid}")->withError('يجب تحديد الشهر');
        }

        $result = PlayerLifecycleService::pause((int) $gid, (int) $pid, $month, $reason);

        if (!$result['success']) {
            return $this->redirect("/sa/players/{$pid}")->withError($result['error']);
        }

        return $this->redirect("/sa/players/{$pid}")->withSuccess("تم إيقاف الاشتراك لشهر {$month}");
    }

    public function resume(Request $request, string $pid, string $gid): Response
    {
        $month = trim((string) $request->post('month', ''));

        if ($month === '') {
            return $this->redirect("/sa/players/{$pid}")->withError('يجب تحديد الشهر');
        }

        $result = PlayerLifecycleService::resume((int) $gid, (int) $pid, $month);

        if (!$result['success']) {
            return $this->redirect("/sa/players/{$pid}")->withError($result['error']);
        }

        return $this->redirect("/sa/players/{$pid}")->withSuccess("تم استئناف الاشتراك لشهر {$month}");
    }

    public function extendGrace(Request $request, string $pid, string $gid): Response
    {
        $days = (int) $request->post('extra_days', 14);

        $enrollment = \App\Core\App::getInstance()->db()->selectOne(
            "SELECT id FROM sa_group_players WHERE group_id = ? AND player_id = ? AND status IN ('active','pending_payment')",
            [(int) $gid, (int) $pid]
        );

        if (!$enrollment) {
            return $this->redirect("/sa/players/{$pid}")->withError('التسجيل غير موجود');
        }

        $result = PlayerLifecycleService::extendMedicalGrace((int) $enrollment['id'], $days);

        if (!$result['success']) {
            return $this->redirect("/sa/players/{$pid}")->withError($result['error']);
        }

        return $this->redirect("/sa/players/{$pid}")
            ->withSuccess("تم تمديد مهلة الشهادة الطبية حتى {$result['new_deadline']}");
    }
}
