<?php
declare(strict_types=1);

namespace App\Modules\TrainingGroups\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\App;
use App\Modules\TrainingGroups\Models\GroupTransferRequest;
use App\Modules\TrainingGroups\Services\GroupTransferService;

class TransferRequestController extends Controller
{
    public function index(Request $request): mixed
    {
        $this->authorize('training_group.manage');
        $status = $_GET['status'] ?? 'pending';
        $requests = GroupTransferRequest::search(['status' => $status !== 'all' ? $status : '']);
        return $this->view('TrainingGroups.Views.transfer_requests', compact('requests', 'status'));
    }

    public function create(Request $request): mixed
    {
        $this->authorize('training_group.manage');
        $db = App::getInstance()->db();
        $groups = $db->select("SELECT id, name_ar FROM training_groups WHERE is_active = 1 ORDER BY name_ar");
        return $this->view('TrainingGroups.Views.transfer_request_create', compact('groups'));
    }

    public function store(Request $request): mixed
    {
        $this->authorize('training_group.manage');
        $data = $_POST;

        $this->validate($data, [
            'player_id'     => 'required',
            'from_group_id' => 'required',
        ]);

        GroupTransferService::submitRequest(
            (int) $data['player_id'],
            (int) $data['from_group_id'],
            !empty($data['to_group_id']) ? (int) $data['to_group_id'] : null,
            $data['reason_ar'] ?? ''
        );

        return $this->redirect('/transfer-requests')->withSuccess('تم تقديم طلب النقل');
    }

    public function approve(Request $request, int $id): mixed
    {
        $this->authorize('training_group.manage');
        $reviewedBy = (int) ($_SESSION['employee_id'] ?? 0);
        $result = GroupTransferService::approveRequest($id, $reviewedBy);
        if (!$result) {
            return $this->redirect('/transfer-requests')->withError('لم يتم العثور على الطلب');
        }
        return $this->redirect('/transfer-requests')->withSuccess('تم قبول طلب النقل');
    }

    public function reject(Request $request, int $id): mixed
    {
        $this->authorize('training_group.manage');
        $reviewedBy = (int) ($_SESSION['employee_id'] ?? 0);
        $notes = $_POST['notes'] ?? '';
        GroupTransferService::rejectRequest($id, $reviewedBy, $notes);
        return $this->redirect('/transfer-requests')->withSuccess('تم رفض طلب النقل');
    }
}
