<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\{Auth, Csrf, Response};
use App\Models\{Package, Subscription};
use Throwable;

class SubscriptionController extends BaseController
{
    private ?array $jsonPayload = null;

    public function subscribers(): Response
    {
        if (!Auth::check()) {
            return Response::json(['ok' => false, 'message' => 'Giris yapmalisin.'], 403);
        }

        if (!$this->isCreatorArea()) {
            return Response::json(['ok' => false, 'message' => 'Aboneleri sadece creator hesaplari gorebilir.'], 403);
        }

        try {
            return Response::json([
                'ok' => true,
                'subscribers' => (new Subscription())->listSubscribersForCreator((int) Auth::id()),
            ]);
        } catch (Throwable $exception) {
            $this->logException($exception, 'subscription.subscribers');

            return Response::json(['ok' => false, 'message' => 'Abone listesi yuklenemedi.'], 500);
        }
    }

    public function mySubscriptions(): Response
    {
        if (!Auth::check()) {
            return Response::json(['ok' => false, 'message' => 'Giris yapmalisin.'], 403);
        }

        try {
            return Response::json([
                'ok' => true,
                'subscriptions' => (new Subscription())->listForSubscriber((int) Auth::id()),
            ]);
        } catch (Throwable $exception) {
            $this->logException($exception, 'subscription.mySubscriptions');

            return Response::json(['ok' => false, 'message' => 'Abonelikler yuklenemedi.'], 500);
        }
    }

    public function preview(): Response
    {
        if (!Csrf::verify((string) ($this->payload()['_csrf'] ?? ''))) {
            return Response::json(['ok' => false, 'message' => 'Guvenlik oturumu yenilenmeli.'], 419);
        }

        $packageId = (int) ($this->payload()['package_id'] ?? $this->payload()['id'] ?? 0);
        $duration = (int) ($this->payload()['duration_months'] ?? $this->payload()['duration'] ?? 1);
        if (!in_array($duration, [1, 6, 12], true)) {
            $duration = 1;
        }

        if ($packageId <= 0) {
            return Response::json(['ok' => false, 'message' => 'Paket hedefi gecersiz.'], 422);
        }

        try {
            $package = (new Package())->findPublic($packageId);
            if (!$package || ($package['status'] ?? 'inactive') !== 'active') {
                return Response::json(['ok' => false, 'message' => 'Bu paket su anda aktif degil.'], 404);
            }

            $preview = (new Subscription())->previewPrice($package, $duration);

            return Response::json([
                'ok' => true,
                'checkout_available' => false,
                'preview' => $preview,
            ]);
        } catch (Throwable $exception) {
            $this->logException($exception, 'subscription.preview');

            return Response::json(['ok' => false, 'message' => 'Abonelik onizlemesi hazirlanamadi.'], 500);
        }
    }

    private function isCreatorArea(): bool
    {
        return in_array((string) (Auth::user()['role'] ?? ''), ['creator', 'admin'], true);
    }

    private function payload(): array
    {
        if ($_POST !== []) {
            return $_POST;
        }

        if ($this->jsonPayload !== null) {
            return $this->jsonPayload;
        }

        $decoded = json_decode(file_get_contents('php://input') ?: '', true);
        $this->jsonPayload = is_array($decoded) ? $decoded : [];

        return $this->jsonPayload;
    }
}
