<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PricingRule;
use App\Models\Accommodation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;

class PricingRuleController extends Controller
{
    /**
     * Display a listing of all pricing rules.
     */
    public function index()
    {
        // Get all accommodations with their pricing rules
        $accommodations = Accommodation::where('status', true)
            ->with('pricingRule')
            ->orderBy('room_category')
            ->orderBy('room_name')
            ->get()
            ->map(function ($accommodation) {
                $pricingRule = $accommodation->pricingRule;
                return [
                    'id' => $accommodation->id,
                    'name' => $accommodation->room_category ?? $accommodation->room_name,
                    'room_category' => $accommodation->room_category,
                    'has_pricing_rule' => $pricingRule !== null,
                    'pricing_rule_id' => $pricingRule?->id,
                    'base_price_bif' => $pricingRule?->base_price_bif ?? $accommodation->price_fbu ?? 0,
                    'base_price_usd' => $pricingRule?->base_price_usd ?? $accommodation->price_usd ?? 0,
                    'base_price_eur' => $pricingRule?->base_price_eur ?? $accommodation->price_eur ?? 0,
                    'additional_adult_bif' => $pricingRule?->additional_adult_bif ?? 0,
                    'additional_adult_usd' => $pricingRule?->additional_adult_usd ?? 0,
                    'additional_adult_eur' => $pricingRule?->additional_adult_eur ?? 0,
                    'child_surcharge_bif' => $pricingRule?->child_surcharge_bif ?? 0,
                    'child_surcharge_usd' => $pricingRule?->child_surcharge_usd ?? 0,
                    'child_surcharge_eur' => $pricingRule?->child_surcharge_eur ?? 0,
                ];
            });

        return Inertia::render('pricing_rules/PricingRule', [
            'accommodations' => $accommodations,
        ]);
    }

    /**
     * Show the form for editing the specified pricing rule.
     */
    public function edit($id)
    {
        $accommodation = Accommodation::findOrFail($id);
        $pricingRule = $accommodation->pricingRule;

        // If pricing rule doesn't exist, create a default one based on accommodation prices
        if (!$pricingRule) {
            $pricingRule = new PricingRule([
                'accommodation_id' => $accommodation->id,
                'base_price_bif' => $accommodation->price_fbu ?? 0,
                'base_price_usd' => $accommodation->price_usd ?? 0,
                'base_price_eur' => $accommodation->price_eur ?? 0,
                'additional_adult_bif' => 0,
                'additional_adult_usd' => 0,
                'additional_adult_eur' => 0,
                'child_surcharge_bif' => 20000,
                'child_surcharge_usd' => 10,
                'child_surcharge_eur' => 8,
            ]);
        }

        return response()->json([
            'id' => $pricingRule->id ?? null,
            'accommodation_id' => $accommodation->id,
            'accommodation_name' => $accommodation->room_category ?? $accommodation->room_name,
            'base_price_bif' => $pricingRule->base_price_bif,
            'base_price_usd' => $pricingRule->base_price_usd,
            'base_price_eur' => $pricingRule->base_price_eur,
            'additional_adult_bif' => $pricingRule->additional_adult_bif,
            'additional_adult_usd' => $pricingRule->additional_adult_usd,
            'additional_adult_eur' => $pricingRule->additional_adult_eur,
            'child_surcharge_bif' => $pricingRule->child_surcharge_bif,
            'child_surcharge_usd' => $pricingRule->child_surcharge_usd,
            'child_surcharge_eur' => $pricingRule->child_surcharge_eur,
        ]);
    }

    /**
     * Update the specified pricing rule in storage.
     */
    public function update(Request $request, $id)
    {
        try {
            DB::beginTransaction();

            $validatedData = $request->validate([
                'accommodation_id' => 'required|exists:accommodations,id',
                'base_price_bif' => 'required|numeric|min:0',
                'base_price_usd' => 'required|numeric|min:0',
                'base_price_eur' => 'required|numeric|min:0',
                'additional_adult_bif' => 'nullable|numeric|min:0',
                'additional_adult_usd' => 'nullable|numeric|min:0',
                'additional_adult_eur' => 'nullable|numeric|min:0',
                'child_surcharge_bif' => 'nullable|numeric|min:0',
                'child_surcharge_usd' => 'nullable|numeric|min:0',
                'child_surcharge_eur' => 'nullable|numeric|min:0',
            ]);

            // Use updateOrCreate to handle both new and existing pricing rules
            $pricingRule = PricingRule::updateOrCreate(
                ['accommodation_id' => $validatedData['accommodation_id']],
                [
                    'base_price_bif' => $validatedData['base_price_bif'],
                    'base_price_usd' => $validatedData['base_price_usd'],
                    'base_price_eur' => $validatedData['base_price_eur'],
                    'additional_adult_bif' => $validatedData['additional_adult_bif'] ?? 0,
                    'additional_adult_usd' => $validatedData['additional_adult_usd'] ?? 0,
                    'additional_adult_eur' => $validatedData['additional_adult_eur'] ?? 0,
                    'child_surcharge_bif' => $validatedData['child_surcharge_bif'] ?? 0,
                    'child_surcharge_usd' => $validatedData['child_surcharge_usd'] ?? 0,
                    'child_surcharge_eur' => $validatedData['child_surcharge_eur'] ?? 0,
                ]
            );

            DB::commit();

            return Redirect::back()->with('success', [
                'message' => 'Pricing rule updated successfully',
                'check' => false
            ]);
        } catch (ValidationException $e) {
            DB::rollBack();
            return redirect()->back()
                ->withErrors($e->errors())
                ->withInput();
        } catch (\Exception $e) {
            DB::rollBack();
            return Redirect::back()->with('error', [
                'message' => 'Error updating pricing rule: ' . $e->getMessage(),
                'check' => false
            ]);
        }
    }
}
