<?php
// app/Http/Controllers/AddressController.php

namespace App\Http\Controllers;

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

class AddressController extends Controller
{
    /**
     * Route yang diizinkan untuk redirect_to (whitelist keamanan)
     */
    private array $allowedRedirects = [
        'address.index',
        'cart.checkout.get',
        'cart.index',
        'order.index',
    ];

    public function index(Request $request)
    {
        $addresses = Auth::user()->addresses()->with(['province', 'city', 'district', 'village'])->latest()->get();

        // Ambil redirect_to dari query string
        $redirectTo = $request->query('redirect_to', 'address.index');

        // Validasi whitelist
        if (!in_array($redirectTo, $this->allowedRedirects)) {
            $redirectTo = 'address.index';
        }

        return view('address.index', compact('addresses', 'redirectTo'));
    }
    
    public function create(Request $request)
    {
        $redirectTo = $request->query('redirect_to', 'address.index');

        return view('address.create', compact('redirectTo'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'province_code'  => 'required|exists:indonesia_provinces,code',
            'city_code'      => 'required|exists:indonesia_cities,code',
            'district_code'  => 'required|exists:indonesia_districts,code',
            'village_code'   => 'required|exists:indonesia_villages,code',
            'street'         => 'required|string|max:255',
            'address_detail' => 'required|string',
            'latitude'       => 'nullable|numeric',
            'longitude'      => 'nullable|numeric',
            'recipient_name' => 'required|string|max:255',
            'phone'          => 'required|string|max:20',
        ]);

        $validated['user_id'] = Auth::id();

        $address = Auth::user()->addresses()->create($validated);

        $redirectTo = $request->input('redirect_to', 'address.index');

        // Validasi route untuk keamanan (mencegah open redirect)
        if (!in_array($redirectTo, $this->allowedRedirects)) {
            $redirectTo = 'address.index';
        }

        // Kalau kembali ke checkout, otomatis set alamat yang baru dibuat
        if ($redirectTo === 'cart.checkout.get' || $redirectTo === 'order.index') {
            session(['selected_address_id' => $address->id]);
        }

        return redirect()->route($redirectTo)
            ->with('success', 'Alamat berhasil ditambahkan');
    }

    public function edit(Address $address, Request $request)
    {
        $this->authorizeAddress($address);

        $redirectTo = $request->query('redirect_to', 'address.index');

        return view('address.edit', compact('address', 'redirectTo'));
    }

    public function update(Request $request, Address $address)
    {
        $this->authorizeAddress($address);

        $validated = $request->validate([
            'province_code'  => 'required|exists:indonesia_provinces,code',
            'city_code'      => 'required|exists:indonesia_cities,code',
            'district_code'  => 'required|exists:indonesia_districts,code',
            'village_code'   => 'required|exists:indonesia_villages,code',
            'street'         => 'required|string|max:255',
            'address_detail' => 'required|string',
            'latitude'       => 'nullable|numeric',
            'longitude'      => 'nullable|numeric',
            'recipient_name' => 'required|string|max:255',
            'phone'          => 'required|string|max:20',
        ]);

        $address->update($validated);

        $redirectTo = $request->input('redirect_to', 'address.index');

        // Validasi route untuk keamanan (mencegah open redirect)
        if (!in_array($redirectTo, $this->allowedRedirects)) {
            $redirectTo = 'address.index';
        }

        return redirect()->route($redirectTo)
            ->with('success', 'Alamat berhasil diperbarui');
    }

    public function destroy(Address $address)
    {
        $this->authorizeAddress($address);
        $address->delete();

        return redirect()->route('address.index')
            ->with('success', 'Alamat berhasil dihapus');
    }

    /**
     * Dipakai dari halaman checkout: set session selected_address_id lalu kembali ke checkout
     */
    public function selectForCheckout(Address $address)
    {
        $this->authorizeAddress($address);

        session(['selected_address_id' => $address->id]);

        return back()->with('success', 'Alamat pengiriman berhasil dipilih');
    }

    private function authorizeAddress(Address $address): void
    {
        if ($address->user_id !== Auth::id()) {
            abort(403, 'Alamat ini bukan milik anda');
        }
    }
}