<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Package;
use App\Models\Booking;
use App\Models\Payment;
use App\Models\Setting;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\BookingConfirmationMail;
use App\Mail\PaymentConfirmationMail;

class PackageController extends Controller
{
    public function index(Request $request)
    {
        $packages = Package::where('is_active', true)
            ->withCount(['confirmedBookings as booked_count'])
            ->when($request->category, function ($query, $category) {
                $query->where('category', $category);
            })
            ->when($request->destination, function ($query, $destination) {
                $query->where('destination', $destination);
            })
            ->when($request->min_price, function ($query, $minPrice) {
                $query->where('price', '>=', $minPrice);
            })
            ->when($request->max_price, function ($query, $maxPrice) {
                $query->where('price', '<=', $maxPrice);
            })
            ->when($request->duration, function ($query, $duration) {
                $query->where('duration_days', $duration);
            })
            ->when($request->difficulty, function ($query, $difficulty) {
                $query->where('difficulty_level', $difficulty);
            })
            ->orderBy($request->sort ?? 'created_at', $request->order ?? 'desc')
            ->paginate(12);

        $categories = Package::where('is_active', true)->distinct()->pluck('category');
        $destinations = Package::where('is_active', true)->distinct()->pluck('destination');
        $durations = Package::where('is_active', true)->distinct()->pluck('duration_days')->sort();
        $difficulties = ['easy', 'moderate', 'challenging', 'extreme'];

        return view('packages.index', compact('packages', 'categories', 'destinations', 'durations', 'difficulties'));
    }

    public function show($slug)
    {
        $package = Package::where('slug', $slug)
            ->where('is_active', true)
            ->withCount(['confirmedBookings as booked_count'])
            ->firstOrFail();

        $relatedPackages = Package::where('is_active', true)
            ->where('id', '!=', $package->id)
            ->where('destination', $package->destination)
            ->orWhere('category', $package->category)
            ->take(4)
            ->get();

        return view('packages.show', compact('package', 'relatedPackages'));
    }

    public function book($slug)
    {
        $package = Package::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();

        if (!$package->is_available) {
            return redirect()->route('packages.show', $slug)
                ->with('error', __('This package is currently not available for booking.'));
        }

        $paymentSettings = [
            'flutterwave' => Setting::get('payment_flutterwave_enabled', true),
            'paypal' => Setting::get('payment_paypal_enabled', false),
        ];

        return view('packages.book', compact('package', 'paymentSettings'));
    }

    public function search(Request $request)
    {
        $query = $request->get('q');
        
        $packages = Package::where('is_active', true)
            ->where(function ($q) use ($query) {
                $q->where('title', 'like', "%{$query}%")
                  ->orWhere('description', 'like', "%{$query}%")
                  ->orWhere('destination', 'like', "%{$query}%")
                  ->orWhere('category', 'like', "%{$query}%");
            })
            ->withCount(['confirmedBookings as booked_count'])
            ->paginate(12);

        if ($request->ajax()) {
            return response()->json([
                'packages' => $packages->items(),
                'pagination' => $packages->links()->toHtml(),
                'total' => $packages->total()
            ]);
        }

        return view('packages.search', compact('packages', 'query'));
    }

    public function getAvailability(Request $request, $slug)
    {
        $package = Package::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();

        $people = $request->get('people', 1);
        $date = $request->get('date');

        if (!$package->canBook($people)) {
            return response()->json([
                'available' => false,
                'message' => __('This package cannot accommodate the requested number of people.')
            ]);
        }

        $availableSlots = $package->available_slots_count;
        
        return response()->json([
            'available' => $availableSlots >= $people,
            'available_slots' => $availableSlots,
            'price_per_person' => $package->has_discount ? $package->discount_price : $package->price,
            'total_price' => ($package->has_discount ? $package->discount_price : $package->price) * $people,
            'currency' => $package->currency
        ]);
    }

    public function addToFavorites(Request $request, $slug)
    {
        if (!Auth::check()) {
            return response()->json(['error' => __('Please login to add favorites')], 401);
        }

        $package = Package::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();

        $user = Auth::user();
        $favorites = $user->preferences['favorites'] ?? [];
        
        if (in_array($package->id, $favorites)) {
            $favorites = array_diff($favorites, [$package->id]);
            $message = __('Package removed from favorites');
        } else {
            $favorites[] = $package->id;
            $message = __('Package added to favorites');
        }

        $user->update(['preferences->favorites' => array_values($favorites)]);

        return response()->json([
            'success' => true,
            'message' => $message,
            'is_favorite' => in_array($package->id, $favorites)
        ]);
    }

    public function compare(Request $request)
    {
        $packageIds = $request->get('packages', []);
        
        if (count($packageIds) < 2) {
            return redirect()->route('packages.index')
                ->with('error', __('Please select at least 2 packages to compare.'));
        }

        if (count($packageIds) > 4) {
            return redirect()->route('packages.index')
                ->with('error', __('You can compare maximum 4 packages at a time.'));
        }

        $packages = Package::where('is_active', true)
            ->whereIn('id', $packageIds)
            ->withCount(['confirmedBookings as booked_count'])
            ->get();

        return view('packages.compare', compact('packages'));
    }

    public function getPackageDetails(Request $request, $slug)
    {
        $package = Package::where('slug', $slug)
            ->where('is_active', true)
            ->withCount(['confirmedBookings as booked_count'])
            ->firstOrFail();

        return response()->json([
            'id' => $package->id,
            'title' => $package->title,
            'slug' => $package->slug,
            'description' => $package->description,
            'price' => $package->price,
            'discount_price' => $package->discount_price,
            'formatted_price' => $package->formatted_price,
            'formatted_discount_price' => $package->formatted_discount_price,
            'has_discount' => $package->has_discount,
            'discount_percentage' => $package->discount_percentage,
            'duration_days' => $package->duration_days,
            'destination' => $package->destination,
            'category' => $package->category,
            'difficulty_level' => $package->difficulty_level,
            'max_people' => $package->max_people,
            'min_people' => $package->min_people,
            'available_slots_count' => $package->available_slots_count,
            'main_image' => $package->main_image,
            'images' => $package->images,
            'inclusions' => $package->inclusions,
            'exclusions' => $package->exclusions,
            'highlights' => $package->highlights,
            'itinerary' => $package->itinerary,
            'accommodation_type' => $package->accommodation_type,
            'transportation' => $package->transportation,
            'meeting_point' => $package->meeting_point,
            'what_to_bring' => $package->what_to_bring,
            'is_available' => $package->is_available,
        ]);
    }
}
