<?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['cultural_tour_id'] = $tour->id;

        // Calculate sort_order if not provided
        if (!isset($data['sort_order'])) {
            $data['sort_order'] = TourItinerary::where('cultural_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.'
        ]);
    }

    /**
     * Quick-view defter (ledger) satırı: tek alan anlık kaydeder.
     * Sözleşme: PATCH {field, value} → {success, display_value}
     */
    public function updateField(Request $request, Tour $tour, TourItinerary $itinerary)
    {
        $this->authorize('update', $tour);

        if ($itinerary->cultural_tour_id !== $tour->id) {
            abort(403);
        }

        $request->validate([
            'field' => 'required|string',
            'value' => 'nullable',
        ]);

        $field = $request->field;
        $value = $request->value;

        $allowed = ['day_number', 'title', 'description', 'location'];
        if (!in_array($field, $allowed, true)) {
            return response()->json(['success' => false, 'message' => 'Geçersiz alan.'], 422);
        }

        $value = is_string($value) ? trim($value) : $value;
        if ($value === '') {
            $value = null;
        }

        if ($field === 'title' && $value === null) {
            return response()->json(['success' => false, 'message' => 'Başlık boş bırakılamaz.'], 422);
        }
        $data = [$field => $value];

        if ($field === 'day_number') {
            $day = max(1, (int) $value);
            $data['day_number'] = $day;
            // Yeni gün içinde sona alınır (aynı gün-sıra ikilisi çakışmasın).
            $data['sort_order'] = (int) TourItinerary::where('cultural_tour_id', $tour->id)
                ->where('day_number', $day)
                ->where('id', '!=', $itinerary->id)
                ->max('sort_order') + 1;
        }

        try {
            $itinerary->update($data);

            return response()->json([
                'success' => true,
                'message' => 'Güncellendi.',
                'value' => $data[$field],
                'display_value' => $data[$field],
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Kaydedilemedi.'], 500);
        }
    }

    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:cultural_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('cultural_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);
        }
    }
}
