<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Subscription;
use App\Models\SubscriptionPlan;
use Illuminate\Http\Request;

class SubscriptionController extends Controller
{
    public function index(Request $request)
    {
        $subscriptions = Subscription::with(['doctor.user', 'plan'])
            ->when($request->status, fn($q) =>
                $q->where('status', $request->status)
            )
            ->when($request->plan_id, fn($q) =>
                $q->where('plan_id', $request->plan_id)
            )
            ->latest()
            ->paginate(15)
            ->withQueryString();

        $plans = SubscriptionPlan::all();

        $stats = [
            'total_active'    => Subscription::where('status', 'active')->where('ends_at', '>', now())->count(),
            'total_revenue'   => Subscription::where('status', 'active')->sum('amount_paid'),
            'month_revenue'   => Subscription::where('status', 'active')
                                    ->whereMonth('created_at', now()->month)->sum('amount_paid'),
            'expiring_soon'   => Subscription::where('status', 'active')
                                    ->whereBetween('ends_at', [now(), now()->addDays(7)])->count(),
        ];

        return view('admin.subscriptions.index', compact('subscriptions', 'plans', 'stats'));
    }

    // ===== إدارة الباقات =====

    public function plans()
    {
        $plans = SubscriptionPlan::orderBy('sort_order')->get();
        return view('admin.subscriptions.plans', compact('plans'));
    }

    public function storePlan(Request $request)
    {
        $data = $this->validatePlan($request);
        SubscriptionPlan::create($data);
        return redirect()->route('admin.subscriptions.plans')
            ->with('success', 'تم إضافة الباقة بنجاح');
    }

    public function updatePlan(Request $request, $id)
    {
        $plan = SubscriptionPlan::findOrFail($id);
        $data = $this->validatePlan($request);
        $plan->update($data);
        return redirect()->route('admin.subscriptions.plans')
            ->with('success', 'تم تحديث الباقة');
    }

    public function destroyPlan($id)
    {
        $plan = SubscriptionPlan::findOrFail($id);

        if ($plan->subscriptions()->where('status', 'active')->exists()) {
            return back()->with('error', 'لا يمكن حذف باقة بها اشتراكات نشطة');
        }

        $plan->delete();
        return back()->with('success', 'تم حذف الباقة');
    }

    private function validatePlan(Request $request): array
    {
        return $request->validate([
            'name'                => 'required|string|max:50',
            'name_ar'             => 'required|string|max:50',
            'price_monthly'       => 'required|numeric|min:0',
            'price_yearly'        => 'required|numeric|min:0',
            'max_daily_patients'  => 'required|integer|min:1',
            'show_ads'            => 'boolean',
            'priority_listing'    => 'boolean',
            'video_allowed'       => 'boolean',
            'max_videos'          => 'integer|min:0',
            'is_active'           => 'boolean',
            'sort_order'          => 'integer',
        ]);
    }
}
