<?php

namespace App\Http\Controllers\Agency\DayTour;

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

class DayTourItineraryController extends Controller
{
    use AuthorizesRequests;

    public function index(DayTour $tour)
    {
        $itineraries = $tour->itineraries()
            ->orderBy('sort_order')
            ->get();

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

    public function store(Request $request, DayTour $tour)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'location' => 'nullable|string|max:255',
            'time' => 'nullable|date_format:H:i',
            'duration_minutes' => 'nullable|integer|min:0',
            'activity_type' => 'nullable|string|max:255',
            'sort_order' => 'nullable|integer|min:0',
        ]);

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

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

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

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

    public function edit(DayTour $tour, DayTourItinerary $itinerary)
    {
        return response()->json([
            'success' => true,
            'itinerary' => $itinerary
        ]);
    }

    public function update(Request $request, DayTour $tour, DayTourItinerary $itinerary)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'location' => 'nullable|string|max:255',
            'time' => 'nullable|date_format:H:i',
            'duration_minutes' => 'nullable|integer|min:0',
            'activity_type' => '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, DayTour $tour, DayTourItinerary $itinerary)
    {
        if ($itinerary->day_tour_id !== $tour->id) {
            abort(403);
        }

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

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

        $allowed = ['title', 'description', 'location', 'time', 'duration_minutes', 'activity_type', 'sort_order'];
        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);
        }
        if ($field === 'time' && $value !== null) {
            if (!preg_match('/^([01]\d|2[0-3]):([0-5]\d)/', (string) $value, $m)) {
                return response()->json(['success' => false, 'message' => 'Saat SS:DD biçiminde olmalı.'], 422);
            }
            $value = $m[1] . ':' . $m[2];
        }
        if (in_array($field, ['duration_minutes', 'sort_order'], true) && $value !== null) {
            $value = max(0, (int) $value);
        }

        try {
            $itinerary->update([$field => $value]);

            $display = $value;
            if ($field === 'duration_minutes') {
                $display = $value === null ? '' : $value . ' dk';
            }
            if ($field === 'activity_type') {
                $display = $value ? (DayTourItinerary::ACTIVITY_TYPES[$value] ?? $value) : '';
            }

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

    public function destroy(DayTour $tour, DayTourItinerary $itinerary)
    {
        $itinerary->delete();

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

    public function reorder(Request $request, DayTour $tour)
    {
        $request->validate([
            'items' => 'required|array',
            'items.*.id' => 'required|exists:day_tour_itineraries,id',
            'items.*.sort_order' => 'required|integer|min:0',
        ]);

        DB::beginTransaction();
        try {
            foreach ($request->items as $item) {
                DayTourItinerary::where('id', $item['id'])
                    ->where('day_tour_id', $tour->id)
                    ->update([
                        '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);
        }
    }
}
