<?php

namespace App\Http\Controllers;

use App\Models\Address;
use App\Helpers\ShippingCalculator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravolt\Indonesia\Models\Province;

class AddressController extends Controller
{
    public function create()
    {
        $provinces = Province::orderBy('name')->get();
        return view('address.create', compact('provinces'));
        }

    public function store(Request $request)
    {
        $request->validate([
            'label'          => 'required|string|max:100',
            'receiver_name'  => 'required|string|max:255',
            'phone'          => 'required|string|max:20',
            'province_code'  => 'required|string',
            'city_code'      => 'required|string',
            'district_code'  => 'nullable|string',
            'village_code'   => 'nullable|string',
            'full_address'   => 'required|string|max:500',
        ]);

        $isFirst = Address::where('user_id', Auth::id())->count() === 0;

        Address::create([
            'user_id'        => Auth::id(),
            'label'          => $request->label,
            'receiver_name'  => $request->receiver_name,
            'phone'          => $request->phone,
            'province_code'  => $request->province_code,
            'city_code'      => $request->city_code,      // ← simpan kode kota
            'district_code'  => $request->district_code,
            'village_code'   => $request->village_code,
            'full_address'   => $request->full_address,
            'is_default'     => $isFirst,
        ]);

        return redirect()->route('user.cart.checkout')
            ->with('success', 'Alamat berhasil ditambahkan!');
    }

    public function index()
    {
        $addresses = Address::where('user_id', Auth::id())->latest()->get();
        return view('user.address.index', compact('addresses'));
    }

    public function destroy(Address $address)
    {
        if ($address->user_id !== Auth::id()) abort(403);
        $address->delete();
        return back()->with('success', 'Alamat berhasil dihapus.');
    }

    /**
     * AJAX: Hitung ongkir berdasarkan alamat yang dipilih.
     * Dipanggil dari halaman checkout saat user ganti alamat.
     */
    public function calculateShipping(Request $request)
    {
        $request->validate(['address_id' => 'required|exists:addresses,id']);

        $address = Address::findOrFail($request->address_id);

        if ($address->user_id !== Auth::id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $ongkir = ShippingCalculator::calculate(
            $address->province_code,
            $address->city_code
        );

        $zone = ShippingCalculator::getZoneLabel(
            $address->province_code,
            $address->city_code
        );

        return response()->json([
            'ongkir'           => $ongkir,
            'formatted_ongkir' => ShippingCalculator::format($ongkir),
            'zone'             => $zone,
        ]);
    }
    
    public function edit(Address $address)
{
    if ($address->user_id !== Auth::id()) abort(403);

    $provinces = \Laravolt\Indonesia\Models\Province::orderBy('name')->get();
    $cities    = \Laravolt\Indonesia\Models\City::where('province_code', $address->province_code)
                    ->orderBy('name')->get();

    $selectedDistrict = $address->district_code
        ? \Laravolt\Indonesia\Models\District::where('code', $address->district_code)->first()
        : null;

    $selectedVillage = $address->village_code
        ? \Laravolt\Indonesia\Models\Village::where('code', $address->village_code)->first()
        : null;

    return view('address.edit', compact(
        'address', 'provinces', 'cities', 'selectedDistrict', 'selectedVillage'
    ));
}

public function update(Request $request, Address $address)
{
    if ($address->user_id !== Auth::id()) abort(403);

    $request->validate([
        'label'         => 'required|string|max:100',
        'receiver_name' => 'required|string|max:255',
        'phone'         => 'required|string|max:20',
        'province_code' => 'required|string',
        'city_code'     => 'required|string',
        'district_code' => 'nullable|string',
        'village_code'  => 'nullable|string',
        'full_address'  => 'required|string|max:500',
    ]);

    $address->update([
        'label'         => $request->label,
        'receiver_name' => $request->receiver_name,
        'phone'         => $request->phone,
        'province_code' => $request->province_code,
        'city_code'     => $request->city_code,
        'district_code' => $request->district_code,
        'village_code'  => $request->village_code,
        'full_address'  => $request->full_address,
    ]);

    return redirect()->route('user.cart.checkout')
        ->with('success', 'Alamat berhasil diupdate!');
}
}
