<?php

namespace App\Http\Controllers;

use App\Models\AppSetting;
use App\Models\Frame;
use App\Models\Lens;
use App\Models\Package;
use App\Models\PaymentTransaction;
use App\Models\Subscription;
use App\Models\User;
use App\Models\VendorProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class SuperAdminController extends Controller
{
    public function showLogin()
    {
        if (Auth::check() && Auth::user()->isSuperAdmin()) {
            return redirect()->route('admin.dashboard');
        }
        return view('admin.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt(['email' => $request->email, 'password' => $request->password, 'role' => 'superadmin'])) {
            $request->session()->regenerate();
            return redirect()->route('admin.dashboard');
        }

        return back()->withErrors(['email' => 'Invalid SuperAdmin credentials.']);
    }

    public function dashboard()
    {
        $totalVendors = User::where('role', 'vendor')->count();
        $activeVendors = User::where('role', 'vendor')->where('status', true)->count();
        $totalCustomers = User::where('role', 'customer')->count();
        $totalFrames = Frame::count();
        $totalLenses = Lens::count();
        $totalRevenue = PaymentTransaction::where('status', 'success')->sum('amount');
        $recentVendors = User::where('role', 'vendor')->with(['vendorProfile', 'activeSubscription.package'])->latest()->take(5)->get();
        $recentTransactions = PaymentTransaction::with(['user', 'package'])->latest()->take(5)->get();

        return view('admin.dashboard', compact(
            'totalVendors',
            'activeVendors',
            'totalCustomers',
            'totalFrames',
            'totalLenses',
            'totalRevenue',
            'recentVendors',
            'recentTransactions'
        ));
    }

    public function vendors(Request $request)
    {
        $query = User::where('role', 'vendor')->with(['vendorProfile', 'activeSubscription.package', 'frames', 'lenses']);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhereHas('vendorProfile', fn($vp) => $vp->where('vendor_name', 'like', "%{$search}%"));
            });
        }

        $vendors = $query->latest()->paginate(15);
        $packages = Package::where('is_active', true)->get();

        return view('admin.vendors', compact('vendors', 'packages'));
    }

    public function storeVendor(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'phone' => 'required|unique:users',
            'password' => 'required|min:6',
            'vendor_name' => 'required|string|max:255',
            'address' => 'nullable|string',
            'city' => 'nullable|string',
            'package_id' => 'nullable|exists:packages,id',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'role' => 'vendor',
            'unique_token' => 'Vendor' . rand(100000, 999999),
            'password' => Hash::make($request->password),
            'status' => true,
        ]);

        VendorProfile::create([
            'user_id' => $user->id,
            'vendor_name' => $request->vendor_name,
            'contact_person_name' => $request->name,
            'address' => $request->address,
            'city' => $request->city,
            'whatsapp_number' => $request->phone,
            'is_active' => true,
        ]);

        if ($request->filled('package_id')) {
            $package = Package::find($request->package_id);
            Subscription::create([
                'user_id' => $user->id,
                'package_id' => $package->id,
                'start_date' => now(),
                'expires_at' => now()->addMonths($package->months),
                'status' => 'active',
            ]);
        }

        return back()->with('success', 'Optical Vendor created successfully!');
    }

    public function toggleVendorStatus($id)
    {
        $vendor = User::where('role', 'vendor')->findOrFail($id);
        $vendor->status = !$vendor->status;
        $vendor->save();

        return back()->with('success', 'Vendor status updated successfully.');
    }

    public function packages()
    {
        $packages = Package::withCount('subscriptions')->get();
        return view('admin.packages', compact('packages'));
    }

    public function storePackage(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'months' => 'required|integer|min:1|max:120',
            'price' => 'required|numeric|min:0',
            'payable_charge' => 'required|numeric|min:0',
            'description' => 'nullable|string',
        ]);

        Package::create($request->all());

        return back()->with('success', 'Subscription package created successfully!');
    }

    public function transactions()
    {
        $transactions = PaymentTransaction::with(['user.vendorProfile', 'package'])->latest()->paginate(20);
        return view('admin.transactions', compact('transactions'));
    }

    public function settings()
    {
        $settings = AppSetting::first() ?? AppSetting::create([]);
        $admin = Auth::user();
        $notifications = \App\Models\AppNotification::where('sender_role', 'superadmin')->latest()->take(20)->get();
        return view('admin.settings', compact('settings', 'admin', 'notifications'));
    }

    public function updateSettings(Request $request)
    {
        $settings = AppSetting::first() ?? AppSetting::create([]);

        $data = $request->except(['_token', 'app_logo', 'admin_name', 'admin_email', 'admin_password', 'admin_password_confirmation']);

        // Handle checkboxes/booleans
        $data['force_update'] = $request->has('force_update') ? (bool)$request->force_update : false;
        $data['enable_ar_tryon'] = $request->has('enable_ar_tryon') ? (bool)$request->enable_ar_tryon : false;
        $data['enable_iris_colorizer'] = $request->has('enable_iris_colorizer') ? (bool)$request->enable_iris_colorizer : false;

        // Handle App Logo Upload
        if ($request->hasFile('app_logo')) {
            $path = $request->file('app_logo')->store('branding', 'public');
            $data['app_logo'] = url('storage/' . $path);
        }

        $settings->update($data);

        return back()->with('success', 'Platform settings updated successfully!');
    }

    public function updateAdminProfile(Request $request)
    {
        $admin = Auth::user();

        $request->validate([
            'admin_name' => 'required|string|max:255',
            'admin_email' => 'required|email|unique:users,email,' . $admin->id,
            'admin_password' => 'nullable|min:6|confirmed',
        ]);

        $admin->name = $request->admin_name;
        $admin->email = $request->admin_email;

        if ($request->filled('admin_password')) {
            $admin->password = Hash::make($request->admin_password);
        }

        $admin->save();

        return back()->with('success', 'SuperAdmin profile credentials updated successfully!');
    }

    public function sendTestNotification(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string|max:1000',
            'target_audience' => 'nullable|in:all_users,all_vendors,both',
            'image' => 'nullable|image|max:10240',
        ]);

        $targetAudience = $request->input('target_audience', 'both');

        $imageUrl = null;
        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('notifications', 'public');
            $imageUrl = url('storage/' . $path);
        }

        \App\Models\AppNotification::create([
            'sender_id' => Auth::id(),
            'sender_role' => 'superadmin',
            'target_audience' => $targetAudience,
            'title' => $request->title,
            'message' => $request->message,
            'image_url' => $imageUrl,
        ]);

        $targetLabel = match($targetAudience) {
            'all_users' => 'All Customers',
            'all_vendors' => 'All Optical Vendors',
            'both' => 'Both Customers & Vendors',
        };

        return back()->with('success', "Broadcast push notification sent to {$targetLabel}! 🚀");
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('admin.login');
    }
}
