<?php

namespace App\Http\Controllers\Agency\Supplier;

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

class SupplierPriceController extends Controller
{
    public function storeList(Request $request, Supplier $supplier)
    {
        if ($supplier->agency_id !== Auth::user()->currentAgencyId()) {
            abort(403, 'Yetkisiz işlem.');
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'season_start' => 'required|date',
            'season_end' => 'required|date|after_or_equal:season_start',
            'marketplace_id' => [
                'required',
                'integer',
                \Illuminate\Validation\Rule::exists('marketplaces', 'id')->where(function ($query) {
                    $query->where('agency_id', Auth::user()->currentAgencyId());
                }),
            ],
            'notes' => 'nullable|string',
        ]);

        SupplierPriceList::create([
            'agency_id' => Auth::user()->currentAgencyId(),
            'supplier_id' => $supplier->id,
            'name' => $request->name,
            'season_start' => $request->season_start,
            'season_end' => $request->season_end,
            'marketplace_id' => $request->marketplace_id,
            'is_active' => true,
            'notes' => $request->notes,
        ]);

        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Fiyat listesi sezonu oluşturuldu.'
            ]);
        }

        return back()->with('success', 'Fiyat listesi sezonu oluşturuldu.');
    }

    public function destroyList(SupplierPriceList $list)
    {
        if ($list->agency_id !== Auth::user()->currentAgencyId()) {
            abort(403, 'Yetkisiz işlem.');
        }

        $list->delete();

        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Fiyat listesi sezonu silindi.'
            ]);
        }

        return back()->with('success', 'Fiyat listesi sezonu silindi.');
    }

    public function storeItem(Request $request, SupplierPriceList $list)
    {
        if ($list->agency_id !== Auth::user()->currentAgencyId()) {
            abort(403, 'Yetkisiz işlem.');
        }

        $supplier = $list->supplier;
        $type = $supplier->supplier_type;

        $allowedCurrencies = [];
        if ($list->marketplace) {
            $allowedCurrencies = $list->marketplace->currencies->pluck('code')->toArray();
        }
        if (empty($allowedCurrencies)) {
            $allowedCurrencies = ['TRY', 'USD', 'EUR'];
        }

        $rules = [
            'currency' => ['required', 'string', \Illuminate\Validation\Rule::in($allowedCurrencies)],
            'net_price' => 'required|numeric|min:0',
            'sale_price' => 'required|numeric|min:0',
            'tax_rate' => 'required|numeric|min:0|max:100',
        ];

        // Type specific validation rules
        if ($type === 'hotel') {
            $rules['room_type'] = 'required|in:single,double,triple,child_0_6,child_0_12';
            $rules['board_type'] = 'required|in:BB,HB,FB,UHD,RO';
            $rules['market'] = 'required|in:yerli,yabanci,hepsi';
            $rules['price_type'] = 'required|in:fit,grup,fit_grup';
            $rules['hb_diff'] = 'nullable|numeric|min:0';
        } elseif ($type === 'transportation') {
            $rules['from_location'] = 'required|string|max:150';
            $rules['to_location'] = 'required|string|max:150';
            $rules['vehicle_type'] = 'required|string|max:100';
            $rules['one_way'] = 'required|boolean';
        } elseif ($type === 'restaurant') {
            $rules['menu_name'] = 'required|string|max:150';
            $rules['beverage_included'] = 'required|boolean';
        } elseif ($type === 'insurance') {
            $rules['policy_name'] = 'required|string|max:150';
            $rules['duration_days'] = 'required|integer|min:1';
            $rules['age_limit'] = 'nullable|integer|min:0';
        } elseif ($type === 'visa') {
            $rules['visa_type'] = 'required|string|max:100';
            $rules['country'] = 'required|string|size:2';
        } elseif ($type === 'airline') {
            $rules['route'] = 'required|string|max:150';
            $rules['flight_class'] = 'required|string|max:50';
        }

        $validated = $request->validate($rules);

        $metadata = [];
        $title = '';

        if ($type === 'hotel') {
            $metadata = [
                'room_type' => $validated['room_type'],
                'board_type' => $validated['board_type'],
                'market' => $validated['market'],
                'price_type' => $validated['price_type'],
                'hb_diff' => $validated['hb_diff'] ?? 0,
            ];
            
            $roomLabel = [
                'single' => 'Single',
                'double' => 'Double',
                'triple' => 'Triple',
                'child_0_6' => '0-6 Yaş',
                'child_0_12' => '0-12 Yaş',
            ][$validated['room_type']];
            $marketLabel = [
                'yerli' => 'Yerli',
                'yabanci' => 'Yabancı',
                'hepsi' => 'Yerli & Yabancı',
            ][$validated['market']];
            $priceTypeLabel = [
                'fit' => 'FIT Net',
                'grup' => 'GRUP Net',
                'fit_grup' => 'Grup ve FIT Net',
            ][$validated['price_type']];
            
            $title = "{$roomLabel} - {$validated['board_type']} ({$marketLabel} / {$priceTypeLabel})";
        } elseif ($type === 'transportation') {
            $metadata = [
                'from_location' => $validated['from_location'],
                'to_location' => $validated['to_location'],
                'vehicle_type' => $validated['vehicle_type'],
                'one_way' => $validated['one_way'],
            ];
            $tripType = $validated['one_way'] ? 'Tek Yön' : 'Gidiş-Dönüş';
            $title = "{$validated['from_location']} - {$validated['to_location']} ({$validated['vehicle_type']} / {$tripType})";
        } elseif ($type === 'restaurant') {
            $metadata = [
                'menu_name' => $validated['menu_name'],
                'beverage_included' => $validated['beverage_included'],
            ];
            $bev = $validated['beverage_included'] ? 'İçecek Dahil' : 'İçecek Hariç';
            $title = "{$validated['menu_name']} ({$bev})";
        } elseif ($type === 'insurance') {
            $metadata = [
                'policy_name' => $validated['policy_name'],
                'duration_days' => $validated['duration_days'],
                'age_limit' => $validated['age_limit'] ?? null,
            ];
            $title = "{$validated['policy_name']} - {$validated['duration_days']} Gün";
            if (!empty($validated['age_limit'])) {
                $title .= " (Max {$validated['age_limit']} Yaş)";
            }
        } elseif ($type === 'visa') {
            $metadata = [
                'visa_type' => $validated['visa_type'],
                'country' => $validated['country'],
            ];
            $title = "{$validated['visa_type']} - " . strtoupper($validated['country']);
        } elseif ($type === 'airline') {
            $metadata = [
                'route' => $validated['route'],
                'flight_class' => $validated['flight_class'],
            ];
            $title = "{$validated['route']} ({$validated['flight_class']} Sınıfı)";
        }

        SupplierPriceItem::create([
            'price_list_id' => $list->id,
            'title' => $title,
            'currency' => $validated['currency'],
            'net_price' => $validated['net_price'],
            'sale_price' => $validated['sale_price'],
            'tax_rate' => $validated['tax_rate'],
            'metadata' => $metadata,
        ]);

        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Fiyat öğesi eklendi.'
            ]);
        }

        return back()->with('success', 'Fiyat öğesi eklendi.');
    }

    public function destroyItem(SupplierPriceItem $item)
    {
        if ($item->priceList->agency_id !== Auth::user()->currentAgencyId()) {
            abort(403, 'Yetkisiz işlem.');
        }

        $item->delete();

        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Fiyat satırı silindi.'
            ]);
        }

        return back()->with('success', 'Fiyat satırı silindi.');
    }
}
