<?php

namespace App\Http\Controllers\Agency\Tour;

use App\Http\Controllers\Controller;
use App\Models\Tour\Tour;
use App\Models\Tour\TourItinerary;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TourItineraryController extends Controller
{
    use AuthorizesRequests;

    public function index(Tour $tour)
    {
        $this->authorize('update', $tour);

        $itineraries = $tour->itineraries()
            ->ordered()
            ->get()
            ->groupBy('day_number');

        return view('agency.products.kultur-turlari.itinerary', compact('tour', 'itineraries'));
    }

    public function store(Request $request, Tour $tour)
    {
        $this->authorize('update', $tour);

        $request->validate([
            'day_number' => 'required|integer|min:1',
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'location' => 'nullable|string|max:255',
            'sort_order' => 'nullable|integer|min:0',
        ]);

        $data = $request->all();
        $data['tour_id'] = $tour->id;

        // Calculate sort_order if not provided
        if (!isset($data['sort_order'])) {
            $data['sort_order'] = TourItinerary::where('tour_id', $tour->id)
                    ->where('day_number', $request->day_number)
                    ->max('sort_order') + 1;
        }

        $itinerary = TourItinerary::create($data);

        return response()->json([
            'success' => true,
            'itinerary' => $itinerary,
            'message' => 'Program eklendi.'
        ]);
    }

    public function edit(Tour $tour, TourItinerary $itinerary)
    {
        $this->authorize('update', $tour);

        return response()->json([
            'success' => true,
            'itinerary' => $itinerary
        ]);
    }

    public function update(Request $request, Tour $tour, TourItinerary $itinerary)
    {
        $this->authorize('update', $tour);

        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'location' => 'nullable|string|max:255',
        ]);

        $itinerary->update($request->all());

        return response()->json([
            'success' => true,
            'message' => 'Program güncellendi.'
        ]);
    }

    public function destroy(Tour $tour, TourItinerary $itinerary)
    {
        $this->authorize('update', $tour);

        $itinerary->delete();

        return response()->json([
            'success' => true,
            'message' => 'Program silindi.'
        ]);
    }

    public function reorder(Request $request, Tour $tour)
    {
        $this->authorize('update', $tour);

        $request->validate([
            'items' => 'required|array',
            'items.*.id' => 'required|exists:tour_itineraries,id',
            'items.*.day_number' => 'required|integer|min:1',
            'items.*.sort_order' => 'required|integer|min:0',
        ]);

        DB::beginTransaction();
        try {
            foreach ($request->items as $item) {
                TourItinerary::where('id', $item['id'])
                    ->where('tour_id', $tour->id)
                    ->update([
                        'day_number' => $item['day_number'],
                        'sort_order' => $item['sort_order']
                    ]);
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Program sıralaması güncellendi.'
            ]);

        } catch (\Exception $e) {
            DB::rollback();
            return response()->json([
                'success' => false,
                'message' => 'Sıralama güncellenirken hata oluştu.'
            ], 422);
        }
    }
}
