<?php

namespace App\Http\Controllers\Agency\Supplier;

use App\Http\Controllers\Controller;
use App\Models\Supplier\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SupplierFactSheetController extends Controller
{
    /**
     * Otel bilgi formunu (fact sheet) oluşturur veya günceller.
     */
    public function update(Request $request, Supplier $supplier)
    {
        if ($supplier->agency_id !== Auth::user()->currentAgencyId()) {
            abort(403, 'Yetkisiz işlem.');
        }

        if ($supplier->supplier_type !== 'hotel') {
            return response()->json([
                'success' => false,
                'message' => 'Bilgi formu yalnızca otel tipi tedarikçiler için tanımlanabilir.',
            ], 422);
        }

        $validated = $request->validate([
            'star_rating' => 'nullable|integer|min:1|max:5',
            'total_rooms' => 'nullable|integer|min:0',
            'total_area' => 'nullable|string|max:100',
            'concept' => 'nullable|string|max:150',
            'check_in_time' => 'nullable|string|max:10',
            'check_out_time' => 'nullable|string|max:10',
            'distance_to_airport' => 'nullable|string|max:100',
            'distance_to_center' => 'nullable|string|max:100',
            'distance_to_beach' => 'nullable|string|max:100',
            'description' => 'nullable|string',

            'general_features' => 'nullable|array',
            'general_features.*' => 'nullable|string|max:150',

            'room_types' => 'nullable|array',
            'room_types.*.name' => 'nullable|string|max:150',
            'room_types.*.size' => 'nullable|string|max:50',
            'room_types.*.capacity' => 'nullable|string|max:50',
            'room_types.*.count' => 'nullable|string|max:50',
            'room_types.*.features' => 'nullable|string|max:500',

            'pools' => 'nullable|array',
            'pools.*.name' => 'nullable|string|max:150',
            'pools.*.type' => 'nullable|string|max:100',
            'pools.*.length' => 'nullable|string|max:50',
            'pools.*.width' => 'nullable|string|max:50',
            'pools.*.depth' => 'nullable|string|max:50',
            'pools.*.heated' => 'nullable|string|max:20',

            'meeting_rooms' => 'nullable|array',
            'meeting_rooms.*.name' => 'nullable|string|max:150',
            'meeting_rooms.*.area' => 'nullable|string|max:50',
            'meeting_rooms.*.height' => 'nullable|string|max:50',
            'meeting_rooms.*.theatre' => 'nullable|string|max:50',
            'meeting_rooms.*.classroom' => 'nullable|string|max:50',
            'meeting_rooms.*.ushape' => 'nullable|string|max:50',
            'meeting_rooms.*.banquet' => 'nullable|string|max:50',

            'food_beverages' => 'nullable|array',
            'food_beverages.*.name' => 'nullable|string|max:150',
            'food_beverages.*.type' => 'nullable|string|max:100',
            'food_beverages.*.cuisine' => 'nullable|string|max:150',
        ]);

        // Tamamen boş satırları temizle
        $clean = function (?array $rows) {
            if (!is_array($rows)) return [];
            return array_values(array_filter($rows, function ($row) {
                return is_array($row) && count(array_filter($row, fn ($v) => $v !== null && $v !== '')) > 0;
            }));
        };

        $features = array_values(array_filter($validated['general_features'] ?? [], fn ($v) => $v !== null && $v !== ''));
        $description = ($validated['description'] ?? null);
        if ($description !== null && trim(strip_tags($description)) === '') {
            $description = null;
        }

        $supplier->factSheet()->updateOrCreate(
            ['supplier_id' => $supplier->id],
            [
                'star_rating' => $validated['star_rating'] ?? null,
                'total_rooms' => $validated['total_rooms'] ?? null,
                'total_area' => $validated['total_area'] ?? null,
                'concept' => $validated['concept'] ?? null,
                'check_in_time' => $validated['check_in_time'] ?? null,
                'check_out_time' => $validated['check_out_time'] ?? null,
                'distance_to_airport' => $validated['distance_to_airport'] ?? null,
                'distance_to_center' => $validated['distance_to_center'] ?? null,
                'distance_to_beach' => $validated['distance_to_beach'] ?? null,
                'description' => $description,
                'general_features' => $features,
                'room_types' => $clean($validated['room_types'] ?? []),
                'pools' => $clean($validated['pools'] ?? []),
                'meeting_rooms' => $clean($validated['meeting_rooms'] ?? []),
                'food_beverages' => $clean($validated['food_beverages'] ?? []),
            ]
        );

        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Otel bilgi formu kaydedildi.',
            ]);
        }

        return back()->with('success', 'Otel bilgi formu kaydedildi.');
    }
}
