<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\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 ProfileController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function show(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $full = $db->selectOne(
            "SELECT id, name_ar, name_en, phone, date_of_birth, gender, national_id,
                    member_id, player_type, medical_status, medical_expiry_date,
                    guardian_name, guardian_phone, guardian_relationship,
                    card_status, created_at
             FROM players WHERE id = ?",
            [$player->id]
        );

        $memberInfo = null;
        if (!empty($full['member_id'])) {
            $memberInfo = $db->selectOne(
                "SELECT membership_number, membership_type, membership_status
                 FROM members WHERE id = ?",
                [$full['member_id']]
            );
        }

        $full['membership'] = $memberInfo;

        return $this->successResponse($full);
    }

    public function update(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'phone' => 'nullable|string|max:20',
                'guardian_name' => 'nullable|string|max:200',
                'guardian_phone' => 'nullable|string|max:20',
                'guardian_relationship' => 'nullable|string|max:50',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $updateData = [];
        if (isset($data['phone']) && $data['phone'] !== '') {
            $existing = $db->selectOne(
                "SELECT id FROM players WHERE phone = ? AND id != ?",
                [$data['phone'], $player->id]
            );
            if ($existing) {
                return $this->errorResponse('رقم الهاتف مستخدم بالفعل', 422);
            }
            $updateData['phone'] = $data['phone'];
        }
        if (isset($data['guardian_name'])) {
            $updateData['guardian_name'] = $data['guardian_name'];
        }
        if (isset($data['guardian_phone'])) {
            $updateData['guardian_phone'] = $data['guardian_phone'];
        }
        if (isset($data['guardian_relationship'])) {
            $updateData['guardian_relationship'] = $data['guardian_relationship'];
        }

        if (!empty($updateData)) {
            $db->update('players', $updateData, 'id = ?', [$player->id]);
        }

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