<?php

namespace App\Http\Controllers;

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

class AddressController extends Controller
{
    /**
     * Tampilkan daftar alamat user
     */
    public function index()
    {
        $addresses = Address::with(['province_rel', 'city_rel', 'district_rel', 'village_rel'])
            ->where('user_id', Auth::id())
            ->orderBy('is_default', 'desc')
            ->latest()
            ->get();

        return view('addresses.index', compact('addresses'));
    }

    /**
     * Form Tambah Alamat
     */
    public function create(Request $request)
    {
        $provinces = Province::orderBy('name')->pluck('name', 'code');
        $redirect = $request->get('redirect');
        return view('addresses.create', compact('provinces', 'redirect'));
    }

    /**
     * Simpan Alamat Baru
     */
    public function store(Request $request)
    {
        $request->validate([
            'label'          => 'required|string|max:255',
            'recipient_name' => 'required|string|max:255',
            'phone'          => 'required|string|max:20',
            'address'        => 'required|string',
            'province'       => 'required',
            'city'           => 'required',
            'district'       => 'required',
            'village'        => 'required',
            'postal_code'    => 'nullable|string|max:10',
        ]);

        $userId = Auth::id();
        $isDefault = !Address::where('user_id', $userId)->exists();

        Address::create([
            'user_id'        => $userId,
            'label'          => $request->label,
            'recipient_name' => $request->recipient_name,
            'phone'          => $request->phone,
            'address'        => $request->address,
            'province'       => $request->province, 
            'city'           => $request->city,
            'district'       => $request->district,
            'village'        => $request->village,
            'postal_code'    => $request->postal_code,
            'is_default'     => $isDefault
        ]);

        if ($request->redirect === 'checkout') {
            return redirect()->route('checkout.index')->with('success', 'Alamat berhasil ditambahkan!');
        }

        return redirect()->route('addresses.index')->with('success', 'Alamat baru berhasil disimpan.');
    }

    /**
     * Form Edit Alamat
     */
    public function edit(Address $address)
    {
        if ($address->user_id !== Auth::id()) {
            abort(403, 'Akses ditolak.');
        }

        $provinces = Province::orderBy('name')->pluck('name', 'code');
        return view('addresses.edit', compact('address', 'provinces'));
    }

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

        $request->validate([
            'label'          => 'required|string|max:255',
            'recipient_name' => 'required|string|max:255',
            'phone'          => 'required|string|max:20',
            'address'        => 'required|string',
            'province'       => 'required',
            'city'           => 'required',
            'district'       => 'required',
            'village'        => 'required',
            'postal_code'    => 'nullable|string|max:10',
        ]);

        // Gunakan fill() dan save() atau update() dengan whitelist yang jelas
        $address->update($request->only([
            'label', 'recipient_name', 'phone', 'address', 
            'province', 'city', 'district', 'village', 'postal_code'
        ]));

        return redirect()->route('addresses.index')->with('success', 'Alamat diperbarui.');
    }

    /**
     * Hapus Alamat
     */
    public function destroy(Address $address)
    {
        if ($address->user_id !== Auth::id()) {
            abort(403);
        }

        if ($address->is_default) {
            $anotherAddress = Address::where('user_id', Auth::id())
                ->where('id', '!=', $address->id)
                ->first();
            
            if ($anotherAddress) {
                $anotherAddress->update(['is_default' => true]);
            }
        }

        $address->delete();
        return back()->with('success', 'Alamat berhasil dihapus.');
    }

    /**
     * Set Alamat Utama
     */
    public function setDefault(Address $address)
    {
        if ($address->user_id !== Auth::id()) {
            abort(403);
        }

        Address::where('user_id', Auth::id())->update(['is_default' => false]);
        $address->update(['is_default' => true]);

        return back()->with('success', 'Alamat utama berhasil diperbarui.');
    }
}