<?php
// app/Http/Controllers/Admin/HotelController.php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Hotel;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class HotelController extends Controller
{
    public function index()
    {
        $hotels = Hotel::withCount(['users', 'rooms'])->latest()->paginate(10);
        $stats = [
            'total' => Hotel::count(),
            'active' => Hotel::where('status', 'active')->count(),
            'trial' => Hotel::where('status', 'trial')->count(),
            'suspended' => Hotel::where('status', 'suspended')->count(),
            'monthly_revenue' => Hotel::where('status', 'active')->sum('monthly_price'),
        ];
        
        return view('admin.hotels.index', compact('hotels', 'stats'));
    }

    public function create()
    {
        $packages = Hotel::PACKAGES;
        return view('admin.hotels.create', compact('packages'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:hotels',
            'phone' => 'required|string|max:20',
            'address' => 'required|string',
            'city' => 'required|string|max:255',
            'country' => 'required|string|max:255',
            'license_number' => 'nullable|string|max:255',
            'tax_id' => 'nullable|string|max:255',
            'website' => 'nullable|url|max:255',
            'package' => 'required|in:silver,gold,platinum,custom',
            'billing_cycle' => 'required|in:monthly,quarterly,yearly',
        ]);

        $validated['slug'] = Str::slug($validated['name']) . '-' . Str::random(6);
        
        // Set package defaults
        $package = Hotel::PACKAGES[$validated['package']];
        $validated['max_rooms'] = $package['max_rooms'];
        $validated['max_users'] = $package['max_users'];
        $validated['monthly_price'] = $package['monthly_price'];
        
        // Set enabled modules based on package
        $validated['enabled_modules'] = array_keys(array_filter($package['features']));
        
        // Set subscription dates
        $validated['subscription_starts_at'] = now();
        $validated['subscription_ends_at'] = now()->addMonth();
        $validated['trial_ends_at'] = now()->addDays(30);
        
        Hotel::create($validated);
        
        return redirect()->route('admin.hotels.index')
                        ->with('success', 'Hotel created successfully.');
    }

    public function show(Hotel $hotel)
    {
        $hotel->loadCount(['users', 'rooms']);
        $usage = [
            'users_percentage' => ($hotel->users_count / $hotel->max_users) * 100,
            'rooms_percentage' => ($hotel->rooms_count / $hotel->max_rooms) * 100,
        ];
        
        return view('admin.hotels.show', compact('hotel', 'usage'));
    }

    public function edit(Hotel $hotel)
    {
        $packages = Hotel::PACKAGES;
        return view('admin.hotels.edit', compact('hotel', 'packages'));
    }

    public function update(Request $request, Hotel $hotel)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:hotels,email,' . $hotel->id,
            'phone' => 'required|string|max:20',
            'address' => 'required|string',
            'city' => 'required|string|max:255',
            'country' => 'required|string|max:255',
            'license_number' => 'nullable|string|max:255',
            'tax_id' => 'nullable|string|max:255',
            'website' => 'nullable|url|max:255',
            'package' => 'required|in:silver,gold,platinum,custom',
            'billing_cycle' => 'required|in:monthly,quarterly,yearly',
            'status' => 'required|in:active,trial,suspended,cancelled',
            'max_rooms' => 'required|integer|min:1',
            'max_users' => 'required|integer|min:1',
            'monthly_price' => 'required|numeric|min:0',
        ]);
        
        $hotel->update($validated);
        
        return redirect()->route('admin.hotels.index')
                        ->with('success', 'Hotel updated successfully.');
    }

    public function destroy(Hotel $hotel)
    {
        $hotel->delete();
        
        return redirect()->route('admin.hotels.index')
                        ->with('success', 'Hotel deleted successfully.');
    }

    public function dashboard()
    {
        $stats = [
            'total_hotels' => Hotel::count(),
            'active_hotels' => Hotel::where('status', 'active')->count(),
            'trial_hotels' => Hotel::where('status', 'trial')->count(),
            'expiring_soon' => Hotel::where('subscription_ends_at', '<', now()->addDays(7))
                                    ->where('subscription_ends_at', '>', now())
                                    ->count(),
            'revenue' => Hotel::where('status', 'active')->sum('monthly_price'),
        ];
        
        $recentHotels = Hotel::latest()->take(5)->get();
        $packageDistribution = Hotel::select('package', DB::raw('count(*) as total'))
                                   ->groupBy('package')
                                   ->get();
        
        return view('admin.dashboard', compact('stats', 'recentHotels', 'packageDistribution'));
    }
}