<?php

namespace App\Http\Controllers;

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

class AddressController extends Controller
{
    public function create()
    {
        $provinces = DB::table('provinces')->get(['id', 'name']);
        return view('address.create', compact('provinces'));
    }

    /**
     * Mengambil daftar kartu alamat saja (untuk pembaruan UI otomatis)
     */
    public function getCards()
    {
        $addresses = Address::where('user_id', Auth::id())->latest()->get();
        return view('jasa.partials.address_cards', compact('addresses'));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama_penerima'  => 'required|string|max:255',
            'nomor_telepon'  => 'required|string|max:255',
            'province_id'    => 'required',
            'regency_id'     => 'required',
            'district_id'    => 'required',
            'village_id'     => 'required',
            'alamat_lengkap' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Lengkapi data: ' . implode(', ', $validator->errors()->all())
            ], 422);
        }

        try {
            $pName = DB::table('provinces')->where('id', $request->province_id)->value('name');
            $rName = DB::table('regencies')->where('id', $request->regency_id)->value('name');
            $dName = DB::table('districts')->where('id', $request->district_id)->value('name');
            $vName = DB::table('villages')->where('id', $request->village_id)->value('name');

            $fullAddress = "{$request->alamat_lengkap} ({$vName}, {$dName}, {$rName}, {$pName})";

            $address = Address::create([
                'user_id'        => Auth::id(),
                'nama_penerima'  => $request->nama_penerima,
                'no_hp'          => $request->nomor_telepon,
                'province_id'    => $request->province_id,
                'regency_id'     => $request->regency_id,
                'district_id'    => $request->district_id,
                'village_id'     => $request->village_id,
                'alamat_lengkap' => $fullAddress,
            ]);

            return response()->json([
                'success' => true,
                'address' => $address
            ]);

        } catch (\Exception $e) {
            Log::error('SIMPAN_ALAMAT: ' . $e->getMessage());
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function getRegencies($province_id) { return response()->json(DB::table('regencies')->where('province_id', $province_id)->get(['id', 'name'])); }
    public function getDistricts($regency_id) { return response()->json(DB::table('districts')->where('regency_id', $regency_id)->get(['id', 'name'])); }
    public function getVillages($district_id) { return response()->json(DB::table('villages')->where('district_id', $district_id)->get(['id', 'name'])); }

    public function destroy($id)
    {
        $address = Address::where('id', $id)->where('user_id', Auth::id())->first();
        if ($address) {
            $address->delete();
            return response()->json(['success' => true]);
        }
        return response()->json(['success' => false], 404);
    }
}