<?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 CarnetController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

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

        if (empty($player->member_id)) {
            return $this->errorResponse('الكارنيه متاح للأعضاء فقط', 403);
        }

        $carnet = $db->selectOne(
            "SELECT id, carnet_number, total_invitations, used_invitations, status, issued_at
             FROM carnets WHERE member_id = ? AND status = 'active'
             ORDER BY issued_at DESC LIMIT 1",
            [$player->member_id]
        );

        if (!$carnet) {
            return $this->successResponse(['has_carnet' => false]);
        }

        $carnet['remaining_invitations'] = (int) $carnet['total_invitations'] - (int) $carnet['used_invitations'];
        $carnet['has_carnet'] = true;

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

    public function invite(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'guest_name' => 'required|string|max:200',
                'guest_phone' => 'nullable|string|max:20',
                'guest_national_id' => 'nullable|string|max:20',
                'activity_type' => 'required|string|in:free_swim,court_booking,recreation,ping_pong,bowling,playstation,tennis,paddle,gym',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

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

        if (empty($player->member_id)) {
            return $this->errorResponse('الكارنيه متاح للأعضاء فقط', 403);
        }

        $carnet = $db->selectOne(
            "SELECT id, total_invitations, used_invitations FROM carnets WHERE member_id = ? AND status = 'active' ORDER BY issued_at DESC LIMIT 1",
            [$player->member_id]
        );

        if (!$carnet) {
            return $this->errorResponse('لا يوجد كارنيه نشط', 422);
        }

        if ((int) $carnet['used_invitations'] >= (int) $carnet['total_invitations']) {
            return $this->errorResponse('تم استنفاد جميع الدعوات', 422);
        }

        $db->insert('carnet_guest_entries', [
            'carnet_id' => $carnet['id'],
            'guest_name' => $data['guest_name'],
            'guest_phone' => $data['guest_phone'] ?? null,
            'guest_national_id' => $data['guest_national_id'] ?? null,
            'activity_type' => $data['activity_type'],
            'entry_time' => date('Y-m-d H:i:s'),
            'status' => 'active',
        ]);

        $db->query(
            "UPDATE carnets SET used_invitations = used_invitations + 1 WHERE id = ?",
            [$carnet['id']]
        );

        $remaining = (int) $carnet['total_invitations'] - (int) $carnet['used_invitations'] - 1;

        return $this->successResponse([
            'invited' => true,
            'remaining_invitations' => $remaining,
            'guest_name' => $data['guest_name'],
        ], 201);
    }

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

        if (empty($player->member_id)) {
            return $this->errorResponse('الكارنيه متاح للأعضاء فقط', 403);
        }

        $entries = $db->select(
            "SELECT cge.guest_name, cge.activity_type, cge.entry_time, cge.exit_time, cge.status
             FROM carnet_guest_entries cge
             INNER JOIN carnets c ON c.id = cge.carnet_id
             WHERE c.member_id = ?
             ORDER BY cge.entry_time DESC
             LIMIT 50",
            [$player->member_id]
        );

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