<?php

declare(strict_types=1);

namespace App\Http\Controllers\Subscription;

use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Response;
use App\Models\Subscription\SubscriptionPlan;
use App\Models\Subscription\Subscription;

class SubscriptionPlanController
{
    // ── Admin: list all plans ──────────────────────────────────────────────
    public function listPlans()
    {
        $plans = SubscriptionPlan::orderBy('active', 'desc')
            ->orderBy('price')
            ->get()
            ->map(fn($p) => self::formatPlan($p));

        return Response::json($plans);
    }

    // ── Admin: create plan ─────────────────────────────────────────────────
    public function createPlan(Request $request)
    {
        $data = $request->validate([
            'name'          => 'required|string|max:255',
            'description'   => 'nullable|string',
            'price'         => 'required|numeric|min:0',
            'duration_days' => 'required|integer|min:1',
            'expiry_action' => 'required|in:restrict,warn,auto_deduct',
        ]);

        $plan = SubscriptionPlan::create($data);

        return Response::json(self::formatPlan($plan), 201);
    }

    // ── Admin: update plan ─────────────────────────────────────────────────
    public function updatePlan(Request $request)
    {
        $hashkey = $request->input('hashkey');
        $plan    = SubscriptionPlan::where('hashkey', $hashkey)->firstOrFail();

        $data = $request->validate([
            'name'          => 'sometimes|string|max:255',
            'description'   => 'nullable|string',
            'price'         => 'sometimes|numeric|min:0',
            'duration_days' => 'sometimes|integer|min:1',
            'expiry_action' => 'sometimes|in:restrict,warn,auto_deduct',
            'active'        => 'sometimes|boolean',
        ]);

        $plan->fill($data);
        $plan->save();

        return Response::json(self::formatPlan($plan));
    }

    // ── Admin: toggle plan active/inactive ────────────────────────────────
    public function togglePlan(Request $request)
    {
        $hashkey = $request->input('hashkey');
        $plan    = SubscriptionPlan::where('hashkey', $hashkey)->firstOrFail();
        $plan->active = !$plan->active;
        $plan->save();

        return Response::json(['active' => $plan->active]);
    }

    // ── Admin: list all user subscriptions ────────────────────────────────
    public function listAllSubscriptions(Request $request)
    {
        $status = $request->input('status'); // optional filter

        $query = Subscription::with(['user', 'plan'])
            ->orderByDesc('created_at');

        if ($status) {
            $query->where('status', $status);
        }

        $results = $query->get()->map(fn($s) => self::formatSubscription($s));

        return Response::json($results);
    }

    private static function formatPlan(SubscriptionPlan $plan): array
    {
        return [
            'hashkey'       => $plan->hashkey,
            'name'          => $plan->name,
            'description'   => $plan->description,
            'price'         => $plan->price,
            'duration_days' => $plan->duration_days,
            'expiry_action' => $plan->expiry_action,
            'active'        => $plan->active,
            'created_at'    => $plan->created_at,
        ];
    }

    private static function formatSubscription(Subscription $sub): array
    {
        return [
            'hashkey'        => $sub->hashkey,
            'user'           => [
                'hashkey'  => $sub->user?->hashkey,
                'name'     => $sub->user?->name ?? $sub->user?->fullname,
                'mobile'   => $sub->user?->mobile_number,
            ],
            'plan'           => [
                'hashkey'       => $sub->plan?->hashkey,
                'name'          => $sub->plan?->name,
                'price'         => $sub->plan?->price,
                'expiry_action' => $sub->plan?->expiry_action,
            ],
            'status'         => $sub->status,
            'starts_at'      => $sub->starts_at,
            'expires_at'     => $sub->expires_at,
            'payment_method' => $sub->payment_method,
        ];
    }
}
