<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Traits\AdminAuthTrait;
use App\Models\PermissionsModules;
use App\Models\PermissionsSubModules;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PlanController extends Controller
{
    use AdminAuthTrait;

    public function index(Request $request, Plan $plan)
    {
        $plans = $plan->latest()->get();
        $modules = PermissionsModules::orderByRaw('COALESCE(priority, 999999) ASC')->get();
        foreach ($modules as $module) {
            $submodules = PermissionsSubModules::where('module_id', $module->id)->get();
            $module->submodules = $submodules;
        }
        $user = null;
        $user = User::find($request->id);
        $subscription = null;

        // Check if user is type 2 (customer)
        if ($user && $user->user_type === config('constants.user_types.customer')) {
            // Get active subscription if exists
            $subscription = Subscription::where('user_id', $user->id)
                ->where(function ($query) {
                    $query->where('stripe_status', 'active')->where('cancel_at_period_end', false);
                })
                ->first();
        }
        $data = [
            'plans' => $plans,
            'modules_list' => $modules,  // Separate modules list
            'subscription' => $subscription, // Add subscription status
            'user' => $user,

        ];
        return $this->success($data);
    }


    public function indexForCusomer(Plan $plan, Request $request)
    {
        $plans = $plan->where('active', 1)->latest()->get();
        $modules = PermissionsModules::orderByRaw('COALESCE(priority, 999999) ASC')->get();
        foreach ($modules as $module) {
            $submodules = PermissionsSubModules::where('module_id', $module->id)->get();
            $module->submodules = $submodules;
        }

        // Get current user
        $user = Auth::user();
        $subscription = null;

        // Check if user is type 2 (customer)
        if ($user && $user->user_type === config('constants.user_types.customer')) {
            // Get active subscription if exists
            $subscription = Subscription::where('user_id', $user->id)
                ->where(function ($query) {
                    $query->where('stripe_status', 'active')->where('cancel_at_period_end', false);
                })
                ->first();
        }

        $data = [
            'plans' => $plans,
            'modules_list' => $modules,  // Separate modules list
            'subscription' => $subscription, // Add subscription status
        ];
        return $this->success($data);
    }


    public function store(Request $request)
    {
        return $this->storePlan($request);
    }

    public function show($plan)
    {
        return $this->showPlan($plan);
    }

    public function update(Request $request)
    {
        return $this->updatePlan($request);
    }

    public function destroy($plan)
    {
        return $this->destroyPlan($plan);
    }

    public function subscriptionRequest(Request $request)
    {
        return $this->customerSubscriptionRequest($request);
    }

    public function bankTransferRequestList(Request $request)
    {
        return $this->showbankTransferRequestList($request);
    }

    public function bankTransferRequestDelete($id)
    {
        return $this->handelbankTransferRequestDelete($id);
    }

    public function showRequestOrder(Request $request)
    {
        return $this->handelShowRequestOrder($request);
    }

    public function bankTransferRequestOrderStatus(Request $request)
    {
        return $this->handelBankTransferRequestStatus($request);
    }

    /**
     * Handle Stripe webhook events
     * 
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function handleStripeWebhook(Request $request)
    {
        // Call the method from the trait, but use the processStripeWebhook 
        // method to avoid recursive call
        return $this->processStripeWebhook($request);
    }



    /**
     * Cancel a subscription
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancelUserSubscription(Request $request)
    {
        $planID = $request->input('plan_id');
        $userID = $request->input('user_id');

        $subscription = Subscription::where('plan_id', $planID)
            ->where('user_id', $userID)
            ->where(function ($query) {
                $query->where('stripe_status', 'active')
                    ->orWhere('stripe_status', 'trialing');
            })
            ->first();

        if (!$subscription) {
            return $this->error('Subscription not found', 404);
        }

        try {
            // Cancel at period end in Stripe
            $stripeSubscription = $this->cancelSubscription($subscription->stripe_id, true);
            // Calculate remaining days
            $remainingDays = $subscription->daysRemaining();
            $endDate = now()->addDays($remainingDays);

            // Update local subscription - keep status as active until period ends
            // but mark that it's been canceled
            $subscription->ends_at = $endDate;
            $subscription->cancel_at_period_end = true; // Add this field to track cancellation
            $subscription->stripe_status = 'canceled';
            // Don't change stripe_status to 'canceled' yet - it's still active until period ends
            $subscription->save();

            // Update user's active plan and expiry date
            $user = User::find($userID);
            if ($user) {
                // Keep the active_plan_id until the subscription actually ends
                // This ensures permissions remain active until the end of the billing period
                $user->plan_expire_date = $endDate;
                $user->save();

                // Refresh user's permissions
                $this->createRolesAndPermissions($user);
                $permissions = $this->getUserPermissions($user);
            }

            $response = [
                'subscription' => $subscription,
                'permissions' => $permissions ?? [],
                'end_date' => $endDate->format('Y-m-d H:i:s'),
                'remaining_days' => $remainingDays
            ];

            return $this->success($response, 'Subscription canceled successfully. You will have access until ' . $endDate->format('Y-m-d'));
        } catch (\Exception $e) {
            return $this->error('Failed to cancel subscription: ' . $e->getMessage(), 500);
        }
    }



    public function updateStatus(Request $request)
    {
        $request->validate([
            'active' => 'required|in:0,1',
        ]);
        $plan = Plan::find($request->id);
        if (!$plan) {
            return $this->error('plan not found' . 404);
        }
        $plan->active = $request->input('active');
        $plan->save();
        return $this->success($plan, 'Status update successfully');
    }
}
