<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AddressController extends Controller
{
    public function index(Request $request)
    {
        return response()->json(['success'=>true,'data'=>$request->user()->addresses]);
    }
    public function store(Request $request)
    {
        $data = $request->validate(['name'=>'required','phone'=>'required','address'=>'required','district'=>'required','city'=>'nullable','is_default'=>'boolean']);
        if(($data['is_default']??false)) $request->user()->addresses()->update(['is_default'=>false]);
        $addr = $request->user()->addresses()->create($data);
        return response()->json(['success'=>true,'data'=>$addr],201);
    }
    public function update(Request $request, int $id)
    {
        $addr = $request->user()->addresses()->findOrFail($id);
        $addr->update($request->validate(['name'=>'string','phone'=>'string','address'=>'string','district'=>'string']));
        return response()->json(['success'=>true,'data'=>$addr]);
    }
    public function destroy(Request $request, int $id)
    {
        $request->user()->addresses()->findOrFail($id)->delete();
        return response()->json(['success'=>true,'message'=>'Address deleted.']);
    }
    public function setDefault(Request $request, int $id)
    {
        DB::transaction(function() use($request,$id){
            $request->user()->addresses()->update(['is_default'=>false]);
            $request->user()->addresses()->findOrFail($id)->update(['is_default'=>true]);
        });
        return response()->json(['success'=>true,'message'=>'Default address updated.']);
    }
}
