<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SubscriptionPlan;
use App\Models\UserSubscription;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use DataTables;

class SubscriptionPlanController extends Controller
{
    protected $user;

    public function __construct()
    {
        $this->user = Auth::guard('admin')->user();
    }

    // ── Plans CRUD ────────────────────────────────────────────────────────────

    public function index(Request $request)
    {
        if (is_null($this->user) || !$this->user->can('dashboard.view')) {
            abort(403, 'Access Denied');
        }

        $headerTitle = 'Subscription Plans';

        if ($request->ajax()) {
            return DataTables::of(SubscriptionPlan::latest())
                ->editColumn('is_active', fn($p) => $p->is_active
                    ? '<span class="badge badge-success">Active</span>'
                    : '<span class="badge badge-secondary">Inactive</span>')
                ->editColumn('price', fn($p) => '$' . number_format($p->price, 2))
                ->addColumn('subscribers', fn($p) => $p->subscriptions()->where('status', 'active')->count())
                ->addColumn('actions', fn($p) => view('backend.admin.subscription_plans.partials.actions', compact('p'))->render())
                ->rawColumns(['is_active', 'actions'])
                ->make(true);
        }

        return view('backend.admin.subscription_plans.index', compact('headerTitle'));
    }

    public function add()
    {
        return view('backend.admin.subscription_plans.add', ['headerTitle' => 'Add Plan']);
    }

    public function insert(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'          => 'required|string|max:100',
            'price'         => 'required|numeric|min:0',
            'duration_days' => 'required|integer|min:1',
            'description'   => 'nullable|string',
            'features'      => 'nullable|string',  // newline-separated in form
            'sort_order'    => 'nullable|integer|min:0',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $features = $request->features
            ? array_filter(array_map('trim', explode("\n", $request->features)))
            : [];

        SubscriptionPlan::create([
            'name'          => $request->name,
            'description'   => $request->description,
            'price'         => $request->price,
            'duration_days' => $request->duration_days,
            'features'      => $features ?: null,
            'is_active'     => $request->boolean('is_active', true),
            'sort_order'    => $request->sort_order ?? 0,
        ]);

        return redirect('admin/subscription-plans')->with('success', 'Plan created successfully');
    }

    public function edit($id)
    {
        $plan = SubscriptionPlan::findOrFail($id);
        return view('backend.admin.subscription_plans.edit', [
            'headerTitle' => 'Edit Plan',
            'plan'        => $plan,
        ]);
    }

    public function update(Request $request)
    {
        $plan = SubscriptionPlan::findOrFail($request->plan_id);

        $validator = Validator::make($request->all(), [
            'name'          => 'required|string|max:100',
            'price'         => 'required|numeric|min:0',
            'duration_days' => 'required|integer|min:1',
            'description'   => 'nullable|string',
            'features'      => 'nullable|string',
            'sort_order'    => 'nullable|integer|min:0',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $features = $request->features
            ? array_filter(array_map('trim', explode("\n", $request->features)))
            : [];

        $plan->update([
            'name'          => $request->name,
            'description'   => $request->description,
            'price'         => $request->price,
            'duration_days' => $request->duration_days,
            'features'      => $features ?: null,
            'is_active'     => $request->boolean('is_active'),
            'sort_order'    => $request->sort_order ?? 0,
        ]);

        return redirect('admin/subscription-plans')->with('success', 'Plan updated successfully');
    }

    public function delete($id)
    {
        SubscriptionPlan::findOrFail($id)->delete();
        return redirect()->back()->with('success', 'Plan deleted successfully');
    }

    // ── User Subscriptions management ─────────────────────────────────────────

    public function userSubscriptions(Request $request)
    {
        $headerTitle = 'User Subscriptions';

        if ($request->ajax()) {
            $query = UserSubscription::with(['user', 'plan'])->latest();

            return DataTables::of($query)
                ->addColumn('user_name', fn($s) => $s->user?->name ?? 'N/A')
                ->addColumn('user_email', fn($s) => $s->user?->email ?? 'N/A')
                ->addColumn('plan_name', fn($s) => $s->plan?->name ?? 'N/A')
                ->editColumn('status', function ($s) {
                    return match ($s->status) {
                        'active'    => '<span class="badge badge-success">Active</span>',
                        'expired'   => '<span class="badge badge-secondary">Expired</span>',
                        'cancelled' => '<span class="badge badge-danger">Cancelled</span>',
                        default     => $s->status,
                    };
                })
                ->editColumn('expires_at', fn($s) => $s->expires_at?->format('d M Y') ?? '-')
                ->addColumn('actions', fn($s) => view('backend.admin.subscription_plans.partials.sub_actions', compact('s'))->render())
                ->rawColumns(['status', 'actions'])
                ->make(true);
        }

        $plans = SubscriptionPlan::where('is_active', true)->get();
        $users = User::select('id', 'name', 'email')->limit(500)->get();

        return view('backend.admin.subscription_plans.user_subscriptions',
            compact('headerTitle', 'plans', 'users'));
    }

    // POST: manually grant a subscription to a user (admin action)
    public function grantSubscription(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required|exists:users,id',
            'plan_id' => 'required|exists:subscription_plans,id',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $plan = SubscriptionPlan::findOrFail($request->plan_id);

        UserSubscription::where('user_id', $request->user_id)
            ->where('status', 'active')
            ->update(['status' => 'expired']);

        $now = now();
        UserSubscription::create([
            'user_id'              => $request->user_id,
            'subscription_plan_id' => $plan->id,
            'starts_at'            => $now,
            'expires_at'           => $now->copy()->addDays($plan->duration_days),
            'status'               => 'active',
            'payment_reference'    => 'admin_grant',
        ]);

        return redirect('admin/user-subscriptions')->with('success', 'Subscription granted successfully');
    }

    // DELETE a user subscription
    public function cancelSubscription($id)
    {
        $sub = UserSubscription::findOrFail($id);
        $sub->update(['status' => 'cancelled']);
        return redirect()->back()->with('success', 'Subscription cancelled');
    }
}
