<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ShippingRate;
use App\Models\City;
use App\Models\District;
use App\Models\Village;
use App\Models\Contact;

class ShippingRateController extends Controller
{
    public function search(Request $request)
    {
        // ----------------------------------------------------
        // 1. SETUP DATA DEFAULT (WA, dll)
        // ----------------------------------------------------
        $contact = Contact::select('whatsapp')->first();
        $whatsappNumber = '6281390003110'; // Default
        if ($contact && $contact->whatsapp) {
            $phone = preg_replace('/[^0-9]/', '', $contact->whatsapp);
            if (substr($phone, 0, 1) === '0') {
                $whatsappNumber = '62' . substr($phone, 1);
            } elseif (substr($phone, 0, 2) === '62') {
                $whatsappNumber = $phone;
            }
        }

        // ----------------------------------------------------
        // 2. DATA DROPDOWN AWAL (KOTA ASAL)
        // ----------------------------------------------------
        // Ambil hanya kota yang pernah menjadi ORIGIN di tabel tarif
        $originIds = ShippingRate::distinct()->pluck('origin_city_id');
        $origins   = City::whereIn('id', $originIds)->orderBy('name', 'asc')->get();

        // ----------------------------------------------------
        // 3. PERSISTENCE LOGIC (Menjaga Pilihan User saat Reload)
        // ----------------------------------------------------
        $destCities    = collect([]);
        $destDistricts = collect([]);
        $destVillages  = collect([]);
        $rates         = collect([]);

        // Ambil Inputan
        $selectedOriginId   = $request->input('origin');
        $selectedDestCity   = $request->input('destination_city');
        $selectedDestDist   = $request->input('destination_district');
        $selectedDestVillId = $request->input('destination_village');
        $weight             = $request->input('weight', 1);

        // A. Jika Origin dipilih, load Kota Tujuan yang valid dari Origin tersebut
        if ($selectedOriginId) {
            $destCities = City::whereHas('districts.villages.shippingRates', function($q) use ($selectedOriginId) {
                $q->where('origin_city_id', $selectedOriginId);
            })
            ->orderBy('name', 'asc')
            ->get();
        }

        // B. Jika Kota Tujuan dipilih, load Kecamatan
        if ($selectedDestCity && $selectedOriginId) {
            $cityObj = City::where('name', $selectedDestCity)->first();
            if ($cityObj) {
                $destDistricts = District::where('city_id', $cityObj->id)
                    ->whereHas('villages.shippingRates', function($q) use ($selectedOriginId) {
                        $q->where('origin_city_id', $selectedOriginId);
                    })
                    ->orderBy('name', 'asc')
                    ->get();
            }
        }

        // C. Jika Kecamatan dipilih, load Kelurahan
        if ($selectedDestDist && isset($cityObj)) {
            $distObj = District::where('city_id', $cityObj->id)->where('name', $selectedDestDist)->first();
            if ($distObj) {
                $destVillages = Village::where('district_id', $distObj->id)
                    ->whereHas('shippingRates', function($q) use ($selectedOriginId) {
                        $q->where('origin_city_id', $selectedOriginId);
                    })
                    ->orderBy('name', 'asc')
                    ->get();
            }
        }

        // ----------------------------------------------------
        // 4. EKSEKUSI PENCARIAN (JIKA FORM DISUBMIT LENGKAP)
        // ----------------------------------------------------
        if ($request->filled('origin') && $request->filled('destination_village')) {
            
            $request->validate([
                'origin'              => 'required',
                'destination_village' => 'required',
                'weight'              => 'required|numeric|min:1',
            ]);

            // Query Utama: Origin ID & Dest Village ID
            $rates = ShippingRate::with(['originCity', 'destinationVillage.district.city']) 
                ->where('origin_city_id', $selectedOriginId)
                ->where('destination_village_id', $selectedDestVillId)
                ->get();

            // Hitung Kalkulasi Harga (Normal vs Overweight)
            $rates->transform(function ($rate) use ($weight) {
                $ratePrice = $rate->price;
                $overPrice = $rate->price_over_weight;
                $minWeight = $rate->min_weight;
                $maxWeight = $rate->max_weight;
                
                $normalCost = 0;
                $excessCost = 0;
                $isOver     = false;

                if ($maxWeight && $weight > $maxWeight) {
                    $isOver     = true;
                    $chgNormal  = max($minWeight, $maxWeight); 
                    $normalCost = $chgNormal * $ratePrice;
                    $excess     = ceil($weight - $maxWeight);
                    $excessCost = $excess * $overPrice;
                    
                    $rate->calc_details = [
                        'type' => 'overweight', 'normal_kg' => $chgNormal, 'normal_total' => $normalCost,
                        'excess_kg' => $excess, 'excess_total' => $excessCost
                    ];
                } else {
                    $chgNormal  = max($weight, $minWeight);
                    $normalCost = $chgNormal * $ratePrice;
                    $rate->calc_details = ['type' => 'normal', 'charge_kg' => $chgNormal];
                }

                $rate->final_price   = $normalCost + $excessCost;
                $rate->is_overweight = $isOver;

                return $rate;
            });
        }

        // ----------------------------------------------------
        // 5. RETURN VIEW
        // ----------------------------------------------------
        return view('ShippingRate.index', [
            'rates'           => $rates,
            'origins'         => $origins,       // List Kota Asal
            'destCities'      => $destCities,    // List Kota Tujuan (Filtered)
            'districts'       => $destDistricts, // List Kecamatan (Filtered)
            'villages'        => $destVillages,  // List Kelurahan (Filtered)
            
            // Re-fill Input Values
            'input_origin'        => $selectedOriginId,
            'input_dest_city'     => $selectedDestCity,
            'input_dest_district' => $selectedDestDist,
            'input_dest_village'  => $selectedDestVillId,
            'input_weight'        => $weight,
            'whatsapp_number'     => $whatsappNumber
        ]);
    }
}