<?php

namespace App\Http\Controllers\Epelcon;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\BedType;
use App\Models\BookingType;
use App\Models\ComplementaryItem;
use App\Models\PromoCode;
use App\Models\RoomType;
use Illuminate\Http\Request;

class RoomSettingsController extends Controller
{
    public function index()
    {
        $promos = PromoCode::latest()->get();

        return view('epelcon.roomsettings.index', [
            'promos' => $promos,
            'promoStats' => [
                'active' => $promos->where('status', 'active')->count(),
                'redemptions' => (int) $promos->sum('used_count'),
            ],
            'bedTypes' => BedType::orderBy('name')->get(),
            'bookingTypes' => BookingType::orderBy('name')->get(),
            'complementaryItems' => ComplementaryItem::with('roomType')->orderBy('name')->get(),
            'roomTypes' => RoomType::all(),
        ]);
    }

    public function storeBed(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:80',
            'description' => 'nullable|string|max:255',
        ]);

        BedType::create($data);
        ActivityLog::record('added bed type', 'room_settings', $data['name']);

        return back()->with('success', "Bed type \"{$data['name']}\" added.");
    }

    public function deleteBed(BedType $bed)
    {
        $bed->delete();
        ActivityLog::record('deleted bed type', 'room_settings', $bed->name);

        return back()->with('success', "Bed type \"{$bed->name}\" removed.");
    }

    public function storeBookingType(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:80',
            'commission_percent' => 'nullable|numeric|min:0|max:100',
        ]);

        BookingType::create([
            'name' => $data['name'],
            'commission_percent' => $data['commission_percent'] ?? 0,
        ]);
        ActivityLog::record('added booking type', 'room_settings', $data['name']);

        return back()->with('success', "Booking type \"{$data['name']}\" added.");
    }

    public function deleteBookingType(BookingType $bookingType)
    {
        $bookingType->delete();
        ActivityLog::record('deleted booking type', 'room_settings', $bookingType->name);

        return back()->with('success', "Booking type \"{$bookingType->name}\" removed.");
    }

    public function storeComplementary(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:120',
            'description' => 'nullable|string|max:255',
            'room_type_id' => 'nullable|exists:room_types,id',
        ]);

        ComplementaryItem::create($data);
        ActivityLog::record('added complementary item', 'room_settings', $data['name']);

        return back()->with('success', "Complementary item \"{$data['name']}\" added.");
    }

    public function deleteComplementary(ComplementaryItem $item)
    {
        $item->delete();
        ActivityLog::record('deleted complementary item', 'room_settings', $item->name);

        return back()->with('success', "Complementary item \"{$item->name}\" removed.");
    }

    public function storePromo(Request $request)
    {
        $data = $request->validate([
            'code' => 'required|string|max:30|regex:/^[A-Za-z0-9\-_]+$/',
            'type' => 'required|in:percent,fixed',
            'value' => 'required|numeric|min:0.01',
            'applies_to' => 'required|in:bookings,orders,both',
            'max_uses' => 'nullable|integer|min:0',
            'starts_at' => 'nullable|date',
            'expires_at' => 'nullable|date|after_or_equal:starts_at',
        ], [
            'code.regex' => 'Promo codes may only contain letters, numbers, dashes and underscores.',
        ]);

        $data['code'] = strtoupper($data['code']);

        if ($data['type'] === 'percent' && (float) $data['value'] > 100) {
            return back()->with('error', 'A percentage discount cannot exceed 100%.')->withInput();
        }

        if (PromoCode::where('code', $data['code'])->exists()) {
            return back()->with('error', "Promo code {$data['code']} already exists.")->withInput();
        }

        $data['max_uses'] = $data['max_uses'] ?? 0;
        $data['status'] = 'active';

        PromoCode::create($data);
        ActivityLog::record('created promo code', 'room_settings', $data['code']);

        return back()->with('success', "Promo code {$data['code']} created.");
    }

    public function togglePromo(PromoCode $promo)
    {
        $promo->update(['status' => $promo->status === 'active' ? 'inactive' : 'active']);
        ActivityLog::record('promo ' . $promo->status, 'room_settings', $promo->code);

        return back()->with('success', "Promo {$promo->code} is now {$promo->status}.");
    }
}
