<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Province;
use App\Models\District;
use App\Models\Subdistrict;
use App\Models\City;
use Illuminate\Http\Request;

class AddressController extends Controller
{
    public function index(Request $request)
    {
        $addresses = auth()->user()->addresses()->orderBy('is_primary', 'desc')->get();
        
        // If AJAX request, return JSON
        if ($request->ajax() || $request->wantsJson()) {
            $addressesData = $addresses->map(function ($address) {
                return [
                    'id' => $address->id,
                    'label' => $address->label,
                    'name' => $address->name,
                    'location' => $address->location,
                    'address' => $address->address,
                    'is_primary' => $address->is_primary,
                    'province_id' => $address->province_id,
                    'city_id' => $address->city_id,
                    'district_id' => $address->district_id,
                    'subdistrict_id' => $address->subdistrict_id,
                    'postal_code' => $address->postal_code,
                    'latitude' => $address->latitude,
                    'longitude' => $address->longitude,
                ];
            });
            
            return response()->json([
                'success' => true,
                'addresses' => $addressesData
            ]);
        }
        
        // For regular page load, return view
        return view('account.addresses', compact('addresses'));
    }

    public function provinces()
    {
        $provinces = Province::orderBy('name')->get();


        return [
            'data'  => $provinces,
        ];
    }

    public function cities($provinceId)
    {
        $cities = City::where('province_id', $provinceId)->orderBy('name')->get();

        return [
            'data' => $cities,
        ];
    }

    public function districts($city_id)
    {
        $districts = District::where('city_id', $city_id)->orderBy('name')->get();

        return [
            'data' => $districts,
        ];
    }

    public function villages($districtId)
    {
        $villages = Subdistrict::where('district_id', $districtId)->orderBy('name')->get();

        return [
            'data' => $villages,
        ];
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'label' => 'required|string|max:255',
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:255',
            'province_id' => 'required|exists:provinces,id',
            'city_id' => 'required|exists:cities,id',
            'district_id' => 'required|exists:districts,id',
            'subdistrict_id' => 'required|exists:subdistricts,id',
            'postal_code' => 'required|string|max:10',
            'address' => 'required|string|max:255',
            'latitude' => 'required|numeric|between:-90,90',
            'longitude' => 'required|numeric|between:-180,180',
            'is_primary' => 'boolean'
        ]);

        $address = auth()->user()->addresses()->findOrFail($id);

        $address->update([
            'label' => $request->label,
            'name' => $request->name,
            'phone' => $request->phone,
            'province_id' => $request->province_id,
            'city_id' => $request->city_id,
            'district_id' => $request->district_id,
            'subdistrict_id' => $request->subdistrict_id,
            'postal_code' => $request->postal_code,
            'address' => $request->address,
            'latitude' => $request->latitude,
            'longitude' => $request->longitude,
            'is_primary' => $request->is_primary ?? $address->is_primary,
        ]);

        // Update location names based on selected IDs
        $province = Province::find($request->province_id);
        $city = City::find($request->city_id);
        $district = District::find($request->district_id);
        $subdistrict = Subdistrict::find($request->subdistrict_id);

        $address->update([
            'province_name' => $province?->name,
            'regency_name' => $city?->name,
            'district_name' => $district?->name,
            'village_name' => $subdistrict?->name,
        ]);

        // If set as primary, unset other primary addresses
        if ($request->boolean('is_primary')) {
            auth()->user()->addresses()
                ->where('id', '!=', $address->id)
                ->update(['is_primary' => false]);
        }

        return response()->json([
            'success' => true,
            'message' => __('addresses.address_updated_successfully'),
            'address' => $address->fresh()
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'label' => 'required|string|max:255',
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:255',
            'province_id' => 'required|exists:provinces,id',
            'city_id' => 'required|exists:cities,id',
            'district_id' => 'required|exists:districts,id',
            'subdistrict_id' => 'required|exists:subdistricts,id',
            'address' => 'required|string|max:255',
            'postal_code' => 'required|string|max:10',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'is_primary' => 'boolean'
        ]);

        // Get location names
        $province = Province::find($request->province_id);
        $city = City::find($request->city_id);
        $district = District::find($request->district_id);
        $subdistrict = Subdistrict::find($request->subdistrict_id);

        $address = auth()->user()->addresses()->create([
            'label' => $request->label,
            'name' => $request->name,
            'phone' => $request->phone,
            'province_id' => $request->province_id,
            'city_id' => $request->city_id,
            'district_id' => $request->district_id,
            'subdistrict_id' => $request->subdistrict_id,
            'address' => $request->address,
            'postal_code' => $request->postal_code,
            'latitude' => $request->latitude,
            'longitude' => $request->longitude,
            'is_primary' => $request->is_primary ?? false,
        ]);

        // If set as primary, unset other primary addresses
        if ($request->boolean('is_primary')) {
            auth()->user()->addresses()
                ->where('id', '!=', $address->id)
                ->update(['is_primary' => false]);
        }

        return response()->json([
            'success' => true,
            'message' => __('addresses.address_created_successfully'),
            'address' => $address
        ]);
    }

    public function destroy($id)
    {
        $address = auth()->user()->addresses()->findOrFail($id);
        
        // Don't allow deletion if it's the only address
        if (auth()->user()->addresses()->count() === 1) {
            return response()->json([
                'success' => false,
                'message' => __('addresses.cannot_delete_only_address')
            ], 400);
        }

        $address->delete();

        return response()->json([
            'success' => true,
            'message' => __('addresses.address_deleted_successfully')
        ]);
    }
}
