<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\VipCardOrder;
use App\Models\Settings;
use App\Mail\NewNotification;
use App\Traits\NotificationTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class AdminVipCardOrderController extends Controller
{
    use NotificationTrait;

    /**
     * List all VIP card orders with search/filter
     */
    public function index(Request $request)
    {
        $query = VipCardOrder::with(['user', 'vipCard']);

        // Search by order number or user name/email
        if ($search = $request->search) {
            $query->where(function ($q) use ($search) {
                $q->where('order_number', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($q2) use ($search) {
                      $q2->where('name', 'like', "%{$search}%")
                         ->orWhere('email', 'like', "%{$search}%");
                  });
            });
        }

        // Filter by status
        if ($status = $request->status) {
            $query->where('status', $status);
        }

        // Filter by payment status
        if ($paymentStatus = $request->payment_status) {
            $query->where('payment_status', $paymentStatus);
        }

        $orders = $query->orderBy('created_at', 'desc')->paginate(20);

        return view('admin.vip-card-orders.index', compact('orders'))
            ->with('title', 'VIP Card Orders');
    }

    /**
     * Show order details
     */
    public function show(VipCardOrder $vipCardOrder)
    {
        $vipCardOrder->load(['user', 'vipCard']);

        return view('admin.vip-card-orders.show', compact('vipCardOrder'))
            ->with('title', 'VIP Order #' . $vipCardOrder->order_number);
    }

    /**
     * Approve order: verify payment + activate membership
     */
    public function approve(VipCardOrder $vipCardOrder)
    {
        if ($vipCardOrder->status !== 'pending') {
            return redirect()->back()->with('error', 'Only pending orders can be approved.');
        }

        // Verify payment and activate
        $vipCardOrder->update(['payment_status' => 'verified']);
        $vipCardOrder->activate();

        // Notify user
        $this->sendDirectUserNotification(
            $vipCardOrder->user_id,
            'VIP Membership Activated!',
            "Your {$vipCardOrder->vipCard->name} membership has been activated. Enjoy your VIP benefits until " . $vipCardOrder->expires_at->format('M d, Y') . "!",
            'success',
            $vipCardOrder->id,
            'vip_card_order'
        );

        // Email user
        try {
            $user = $vipCardOrder->user;
            if ($user) {
                $message = "Congratulations! Your {$vipCardOrder->vipCard->name} VIP membership (Order #{$vipCardOrder->order_number}) has been activated. Enjoy your VIP benefits until " . $vipCardOrder->expires_at->format('M d, Y') . "!";
                Mail::to($user->email)->send(new NewNotification($message, 'VIP Membership Activated!', $user->name));
            }
        } catch (\Exception $e) {
            \Log::error('VIP approve email failed: ' . $e->getMessage());
        }

        return redirect()->back()
            ->with('success', 'Order approved and membership activated.');
    }

    /**
     * Decline/reject order
     */
    public function decline(VipCardOrder $vipCardOrder)
    {
        if (!in_array($vipCardOrder->status, ['pending'])) {
            return redirect()->back()->with('error', 'Only pending orders can be declined.');
        }

        $vipCardOrder->update([
            'status'         => 'cancelled',
            'payment_status' => 'failed',
        ]);

        // Notify user
        $this->sendDirectUserNotification(
            $vipCardOrder->user_id,
            'VIP Membership Order Declined',
            "Your order #{$vipCardOrder->order_number} for {$vipCardOrder->vipCard->name} has been declined. Please contact support for details.",
            'danger',
            $vipCardOrder->id,
            'vip_card_order'
        );

        // Email user
        try {
            $user = $vipCardOrder->user;
            if ($user) {
                Mail::to($user->email)->send(new NewNotification(
                    "Your VIP card order #{$vipCardOrder->order_number} for {$vipCardOrder->vipCard->name} has been declined. Please contact support for more details.",
                    'VIP Card Order Declined - #' . $vipCardOrder->order_number,
                    $user->name
                ));
            }
        } catch (\Exception $e) {
            \Log::error('VIP decline email failed: ' . $e->getMessage());
        }

        return redirect()->back()
            ->with('success', 'Order declined.');
    }

    /**
     * Cancel an active membership
     */
    public function cancel(VipCardOrder $vipCardOrder)
    {
        $vipCardOrder->update([
            'status' => 'cancelled',
        ]);

        $this->sendDirectUserNotification(
            $vipCardOrder->user_id,
            'VIP Membership Cancelled',
            "Your {$vipCardOrder->vipCard->name} membership (Order #{$vipCardOrder->order_number}) has been cancelled by an administrator.",
            'warning',
            $vipCardOrder->id,
            'vip_card_order'
        );

        // Email user
        try {
            $user = $vipCardOrder->user;
            if ($user) {
                Mail::to($user->email)->send(new NewNotification(
                    "Your {$vipCardOrder->vipCard->name} VIP membership (Order #{$vipCardOrder->order_number}) has been cancelled. If you believe this is an error, please contact support.",
                    'VIP Membership Cancelled - #' . $vipCardOrder->order_number,
                    $user->name
                ));
            }
        } catch (\Exception $e) {
            \Log::error('VIP cancel email failed: ' . $e->getMessage());
        }

        return redirect()->back()
            ->with('success', 'Membership cancelled.');
    }

    /**
     * Refund an order
     */
    public function refund(VipCardOrder $vipCardOrder)
    {
        $vipCardOrder->update([
            'status' => 'refunded',
        ]);

        $this->sendDirectUserNotification(
            $vipCardOrder->user_id,
            'VIP Membership Refunded',
            "Your {$vipCardOrder->vipCard->name} membership (Order #{$vipCardOrder->order_number}) has been refunded.",
            'info',
            $vipCardOrder->id,
            'vip_card_order'
        );

        // Email user
        try {
            $user = $vipCardOrder->user;
            if ($user) {
                Mail::to($user->email)->send(new NewNotification(
                    "Your {$vipCardOrder->vipCard->name} VIP membership (Order #{$vipCardOrder->order_number}) has been refunded. The amount will be returned to your original payment method.",
                    'VIP Membership Refunded - #' . $vipCardOrder->order_number,
                    $user->name
                ));
            }
        } catch (\Exception $e) {
            \Log::error('VIP refund email failed: ' . $e->getMessage());
        }

        return redirect()->back()
            ->with('success', 'Order refunded.');
    }

    /**
     * Delete order (soft delete)
     */
    public function destroy(VipCardOrder $vipCardOrder)
    {
        $vipCardOrder->delete();

        return redirect()->route('admin.vip-card-orders.index')
            ->with('success', 'Order deleted.');
    }
}
