<?php

namespace App\Http\Controllers;

use App\Models\ShippingZone;
use App\Models\ShippingSetting;
use App\Services\ShippingCalculatorService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShippingController extends Controller
{
    public function __construct(
        private readonly ShippingCalculatorService $calculator
    ) {}

    // ── API: Kalkulasi ongkir (dipanggil AJAX dari halaman checkout) ──────────

    /**
     * POST /api/shipping/calculate
     *
     * Body: { province_code, total_weight_gram, subtotal, courier_code? }
     * Response: JSON { options[], zone, free_shipping, selected? }
     */
    public function calculate(Request $request)
    {
        $request->validate([
            'province_code'     => 'required|string',
            'total_weight_gram' => 'required|integer|min:1',
            'subtotal'          => 'required|integer|min:0',
            'courier_code'      => 'nullable|string',
        ]);

        try {
            $result = $this->calculator->calculate(
                $request->province_code,
                (int) $request->total_weight_gram,
                (int) $request->subtotal,
            );

            // Jika ada kurir yang sudah dipilih, tambahkan info detailnya
            $selected = null;
            if ($request->courier_code && !empty($result['options'])) {
                foreach ($result['options'] as $opt) {
                    if ($opt['code'] === $request->courier_code) {
                        $selected = $opt;
                        break;
                    }
                }
            }

            return response()->json([
                'success'  => true,
                'data'     => array_merge($result, ['selected' => $selected]),
            ]);
        } catch (\Throwable $e) {
            Log::error('Shipping calculate error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghitung ongkir: ' . $e->getMessage(),
            ], 500);
        }
    }

    // ── Admin: Pengaturan Umum ────────────────────────────────────────────────

    public function adminSettings()
    {
        $settings = ShippingSetting::whereNotIn('key', ['courier_services'])->get()->keyBy('key');
        $zones    = ShippingZone::orderBy('sort_order')->get();
        $couriers = ShippingSetting::getCourierServices();

        return view('admin.shipping.settings', compact('settings', 'zones', 'couriers'));
    }

    public function adminSaveSettings(Request $request)
    {
        $request->validate([
            'free_shipping_enabled'   => 'nullable|boolean',
            'free_shipping_minimum'   => 'required|integer|min:0',
            'default_product_weight'  => 'required|integer|min:100',
            'tracking_prefix'         => 'required|string|max:10|regex:/^[A-Z0-9]+$/i',
        ]);

        DB::beginTransaction();
        try {
            ShippingSetting::setValue('free_shipping_enabled', $request->boolean('free_shipping_enabled') ? '1' : '0');
            ShippingSetting::setValue('free_shipping_minimum', $request->free_shipping_minimum);
            ShippingSetting::setValue('default_product_weight', $request->default_product_weight);
            ShippingSetting::setValue('tracking_prefix', strtoupper($request->tracking_prefix));

            ShippingSetting::clearCache();
            DB::commit();

            return back()->with('success', 'Pengaturan pengiriman berhasil disimpan.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Gagal menyimpan pengaturan: ' . $e->getMessage());
        }
    }

    // ── Admin: Manajemen Zona ─────────────────────────────────────────────────

    public function adminZones()
    {
        $zones = ShippingZone::orderBy('sort_order')->get();
        return view('admin.shipping.zones', compact('zones'));
    }

    public function adminZoneStore(Request $request)
    {
        $validated = $request->validate([
            'zone_code'         => 'required|string|max:30|unique:shipping_zones,zone_code|regex:/^[a-z0-9_]+$/',
            'zone_name'         => 'required|string|max:100',
            'description'       => 'nullable|string|max:255',
            'province_codes'    => 'required|array|min:1',
            'province_codes.*'  => 'string',
            'base_price_per_kg' => 'required|integer|min:1000',
            'min_charge_weight' => 'required|integer|min:100',
            'weight_rounding'   => 'required|integer|min:100',
            'sort_order'        => 'nullable|integer|min:0',
        ]);

        ShippingZone::create($validated);

        return back()->with('success', "Zona '{$validated['zone_name']}' berhasil ditambahkan.");
    }

    public function adminZoneUpdate(Request $request, ShippingZone $zone)
    {
        $validated = $request->validate([
            'zone_name'         => 'required|string|max:100',
            'description'       => 'nullable|string|max:255',
            'base_price_per_kg' => 'required|integer|min:1000',
            'min_charge_weight' => 'required|integer|min:100',
            'weight_rounding'   => 'required|integer|min:100',
            'is_active'         => 'nullable|boolean',
            'sort_order'        => 'nullable|integer|min:0',
        ]);

        $validated['is_active'] = $request->boolean('is_active');
        $zone->update($validated);

        return back()->with('success', "Zona '{$zone->zone_name}' berhasil diperbarui.");
    }

    // ── Admin: Manajemen Kurir ────────────────────────────────────────────────
    
    public function adminCourierUpdate(Request $request, string $code)
    {
        $validated = $request->validate([
            'short_name'       => 'required|string|max:50',
            'etd'              => 'required|string|max:50',
            'price_multiplier' => 'required|numeric|min:0.1|max:10',
            'is_active'        => 'nullable|boolean',
        ]);

        $couriers = ShippingSetting::getCourierServices();
        $updated = false;

        foreach ($couriers as &$courier) {
            if ($courier['code'] === $code) {
                $courier['short_name']       = $validated['short_name'];
                $courier['etd']              = $validated['etd'];
                $courier['price_multiplier'] = (float) $validated['price_multiplier'];
                $courier['is_active']        = $request->boolean('is_active');
                $updated = true;
                break;
            }
        }

        if ($updated) {
            ShippingSetting::setValue('courier_services', json_encode(array_values($couriers)));
            ShippingSetting::clearCache();
            return back()->with('success', "Layanan kurir berhasil diperbarui.");
        }

        return back()->with('error', "Layanan kurir tidak ditemukan.");
    }
}
