<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\VipCard;
use App\Models\VipCardOrder;
use App\Models\Wdmethod;
use App\Models\Settings;
use App\Traits\TemplateTrait;
use App\Traits\NotificationTrait;
use App\Mail\NewNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class VipCardController extends Controller
{
    use TemplateTrait, NotificationTrait;

    /**
     * Browse available VIP cards (public-facing, may or may not be auth'd)
     */
    public function index()
    {
        $cards = VipCard::active()
            ->ordered()
            ->get();

        // If authenticated, get user's active memberships
        $activeMemberships = [];
        if (Auth::check()) {
            $activeMemberships = VipCardOrder::forUser(Auth::id())
                ->active()
                ->pluck('vip_card_id')
                ->toArray();
        }

        return view('user.vip-cards.index', compact('cards', 'activeMemberships'))
            ->with('title', 'VIP Card Memberships');
    }

    /**
     * Show single VIP card details
     */
    public function show(VipCard $vipCard)
    {
        if ($vipCard->status !== 'active') {
            abort(404);
        }

        $hasActive = false;
        if (Auth::check()) {
            $hasActive = VipCardOrder::forUser(Auth::id())
                ->where('vip_card_id', $vipCard->id)
                ->active()
                ->exists();
        }

        return view('user.vip-cards.show', compact('vipCard', 'hasActive'))
            ->with('title', $vipCard->name);
    }

    /**
     * Purchase page — select payment method
     */
    public function purchase(VipCard $vipCard)
    {
        if ($vipCard->status !== 'active') {
            return redirect()->route('vip-cards.index')
                ->with('error', 'This VIP card is not available.');
        }

        $paymentMethods = Wdmethod::where('status', 'enabled')->get();
        $user = Auth::user();

        return view('user.vip-cards.purchase', compact('vipCard', 'paymentMethods', 'user'))
            ->with('title', 'Purchase ' . $vipCard->name);
    }

    /**
     * Place the VIP card order
     */
    public function placeOrder(Request $request, VipCard $vipCard)
    {
        $validator = Validator::make($request->all(), [
            'payment_method' => 'required|string|max:255',
        ]);

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

        if ($vipCard->status !== 'active') {
            return redirect()->route('vip-cards.index')
                ->with('error', 'This VIP card is no longer available.');
        }

        $order = VipCardOrder::create([
            'user_id'        => Auth::id(),
            'vip_card_id'    => $vipCard->id,
            'amount'         => $vipCard->price,
            'payment_method' => $request->payment_method,
            'payment_status' => 'pending',
            'status'         => 'pending',
        ]);

        // Notify admin
        $this->sendDirectAdminNotification(
            1,
            'New VIP Card Order',
            "New VIP card order #{$order->order_number} placed by " . Auth::user()->name . " for {$vipCard->name} (\${$vipCard->price}).",
            'info',
            $order->id,
            'vip_card_order'
        );

        // Send order confirmation email to user
        try {
            $user = Auth::user();
            $settings = Settings::where('id', 1)->first();
            $message = "Your VIP card order #{$order->order_number} for {$vipCard->name} has been placed successfully. Amount: \$" . number_format($vipCard->price, 2) . ". Please complete your payment to proceed.";
            Mail::to($user->email)->send(new NewNotification($message, 'VIP Card Order Confirmation - #' . $order->order_number, $user->name));
            // Notify admin via email
            Mail::to($settings->contact_email)->send(new NewNotification(
                "New VIP card order #{$order->order_number} placed by {$user->name} ({$user->email}) for {$vipCard->name}. Amount: \$" . number_format($vipCard->price, 2),
                'New VIP Card Order - #' . $order->order_number,
                'Admin'
            ));
        } catch (\Exception $e) {
            \Log::error('VIP card order email failed: ' . $e->getMessage());
        }

        return redirect()->route('vip-cards.payment', $order->id)
            ->with('success', 'Order created! Now complete your payment below.');
    }

    /**
     * Show payment details page (payment method info + proof upload)
     */
    public function payment(VipCardOrder $order)
    {
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $order->load('vipCard');
        $payment_mode = Wdmethod::where('name', $order->payment_method)->first();

        if (!$payment_mode) {
            return redirect()->route('vip-cards.my-memberships')
                ->with('error', 'Payment method not found.');
        }

        return view('user.vip-cards.payment', compact('order', 'payment_mode'))
            ->with('title', 'Complete Payment - Order #' . $order->order_number);
    }

    /**
     * Upload payment proof
     */
    public function savePaymentProof(Request $request, VipCardOrder $order)
    {
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $validator = Validator::make($request->all(), [
            'payment_proof' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
        ]);

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

        $dir = base_path('dash/vip-payments');
        if (!\File::isDirectory($dir)) {
            \File::makeDirectory($dir, 0755, true);
        }
        $filename = uniqid() . '.' . $request->file('payment_proof')->getClientOriginalExtension();
        $request->file('payment_proof')->move($dir, $filename);

        $order->update([
            'payment_proof' => 'vip-payments/' . $filename,
        ]);

        return redirect()->route('vip-cards.membership-details', $order->id)
            ->with('success', 'Payment proof uploaded successfully! Your order is being reviewed.');
    }

    /**
     * List user's VIP memberships
     */
    public function myMemberships()
    {
        $orders = VipCardOrder::forUser(Auth::id())
            ->with('vipCard')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('user.vip-cards.my-memberships', compact('orders'))
            ->with('title', 'My VIP Memberships');
    }

    /**
     * Show single membership order details
     */
    public function membershipDetails(VipCardOrder $order)
    {
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $order->load('vipCard');

        return view('user.vip-cards.membership-details', compact('order'))
            ->with('title', 'Membership - ' . $order->order_number);
    }
}
