<?php

namespace App\Http\Controllers;

use App\Helpers\ApiResponse;
use App\Models\MembershipPlan;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class MembershipPlanController extends Controller
{
    // ─────────────────────────────────
    // GET ALL ACTIVE PLANS (Public)
    // GET /api/plans
    // ─────────────────────────────────
    public function getActivePlans()
    {
        $plans = MembershipPlan::where('is_active', true)
                               ->get();

        $data = $plans->map(function ($plan) {
            return [
                'id'              => (string) $plan->id,
                'name'            => $plan->name,
                'type'            => $plan->type,
                'amount'          => (string) $plan->amount,
                'duration_months' => (string) $plan->duration_months,
                'description'     => $plan->description,
                'is_active'       => (string) (int) $plan->is_active,
            ];
        });

        return ApiResponse::success(
            $data,
            'Plans fetched successfully'
        );
    }

    // ─────────────────────────────────
    // GET ALL PLANS (Super Admin)
    // GET /api/admin/plans
    // ─────────────────────────────────
    public function getAllPlans()
    {
        $plans = MembershipPlan::latest()->get();

        $data = $plans->map(function ($plan) {
            return [
                'id'              => (string) $plan->id,
                'name'            => $plan->name,
                'type'            => $plan->type,
                'amount'          => (string) $plan->amount,
                'duration_months' => (string) $plan->duration_months,
                'description'     => $plan->description,
                'is_active'       => (string) (int) $plan->is_active,
                'created_at'      => (string) $plan->created_at,
            ];
        });

        return ApiResponse::success(
            $data,
            'Plans fetched successfully'
        );
    }

    // ─────────────────────────────────
    // CREATE PLAN (Super Admin)
    // POST /api/admin/plans
    // ─────────────────────────────────
    public function createPlan(Request $request)
    {
        $request->validate([
            'name'            => 'required|string',
            'type'            => 'required|in:LIFE,ANNUAL',
            'amount'          => 'required|numeric|min:0',
            'duration_months' => 'required|integer|min:0',
            'description'     => 'nullable|string',
        ]);

        // Check if plan type already exists
        $exists = MembershipPlan::where(
            'type', $request->type
        )->first();

        if ($exists) {
            return ApiResponse::error(
                $request->type . ' plan already exists. 
                Update the existing one instead.',
                400
            );
        }

        $plan = MembershipPlan::create([
            'name'            => $request->name,
            'type'            => $request->type,
            'amount'          => $request->amount,
            'duration_months' => $request->duration_months,
            'description'     => $request->description,
            'is_active'       => true,
        ]);

        return ApiResponse::success(
            [
                'id'              => (string) $plan->id,
                'name'            => $plan->name,
                'type'            => $plan->type,
                'amount'          => (string) $plan->amount,
                'duration_months' => (string) $plan->duration_months,
                'description'     => $plan->description,
                'is_active'       => (string) (int) $plan->is_active,
            ],
            'Plan created successfully',
            201
        );
    }

    // ─────────────────────────────────
    // UPDATE PLAN (Super Admin)
    // POST /api/admin/plans/update
    // ─────────────────────────────────
    public function updatePlan(Request $request)
    {
        $request->validate([
            'id'          => 'required|exists:membership_plans,id',
            'name'        => 'sometimes|string',
            'amount'      => 'sometimes|numeric|min:0',
            'description' => 'nullable|string',
        ]);

        $plan = MembershipPlan::find($request->id);

        if ($request->filled('name'))
            $plan->name        = $request->name;
        if ($request->filled('amount'))
            $plan->amount      = $request->amount;
        if ($request->has('description'))
            $plan->description = $request->description;

        $plan->save();

        return ApiResponse::success(
            [
                'id'              => (string) $plan->id,
                'name'            => $plan->name,
                'type'            => $plan->type,
                'amount'          => (string) $plan->amount,
                'duration_months' => (string) $plan->duration_months,
                'description'     => $plan->description,
                'is_active'       => (string) (int) $plan->is_active,
            ],
            'Plan updated successfully'
        );
    }

    // ─────────────────────────────────
    // TOGGLE STATUS (Super Admin)
    // PUT /api/admin/plans/toggle-status
    // ─────────────────────────────────
    public function toggleStatus(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:membership_plans,id'
        ]);

        $plan            = MembershipPlan::find($request->id);
        $plan->is_active = !$plan->is_active;
        $plan->save();

        $status = $plan->is_active ? 'activated' : 'deactivated';

        return ApiResponse::success(
            [
                'id'        => (string) $plan->id,
                'name'      => $plan->name,
                'type'      => $plan->type,
                'is_active' => (string) (int) $plan->is_active,
            ],
            'Plan ' . $status . ' successfully'
        );
    }

    // ─────────────────────────────────
    // DELETE PLAN (Super Admin)
    // DELETE /api/admin/plans
    // ─────────────────────────────────
    public function deletePlan(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:membership_plans,id'
        ]);

        $plan = MembershipPlan::find($request->id);
        $plan->delete();

        return ApiResponse::success(
            null,
            'Plan deleted successfully'
        );
    }
}