<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Core\Exceptions\ValidationException;

final class CoachAuthController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function login(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'phone' => 'required|string',
                'password' => 'required|string',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $db = App::getInstance()->db();
        $coach = $db->selectOne(
            "SELECT id, name_ar, phone, password_hash, is_archived FROM coaches WHERE phone = ? AND is_archived = 0",
            [$data['phone']]
        );

        if (!$coach || empty($coach['password_hash']) || !password_verify($data['password'], $coach['password_hash'])) {
            return $this->errorResponse('رقم الهاتف أو كلمة المرور غير صحيحة', 401);
        }

        $config = App::getInstance()->config('api.token', []);
        $ttlHours = $config['coach_ttl_hours'] ?? 2160;

        $token = bin2hex(random_bytes(32));
        $expiresAt = date('Y-m-d H:i:s', time() + ($ttlHours * 3600));

        $db->insert('coach_tokens', [
            'coach_id' => $coach['id'],
            'token' => $token,
            'name' => 'portal',
            'expires_at' => $expiresAt,
        ]);

        $db->update('coaches', ['last_login_at' => date('Y-m-d H:i:s')], 'id = ?', [$coach['id']]);

        return $this->successResponse([
            'token' => $token,
            'expires_at' => $expiresAt,
            'coach' => [
                'id' => (int) $coach['id'],
                'name' => $coach['name_ar'],
                'phone' => $coach['phone'],
            ],
        ], 201);
    }

    public function logout(Request $request): Response
    {
        $token = $request->bearerToken();
        $db = App::getInstance()->db();
        $db->update('coach_tokens', ['is_revoked' => 1], '`token` = ?', [$token]);

        return $this->successResponse(['logged_out' => true]);
    }
}
