<?php
declare(strict_types=1);

namespace Controllers;
use Helpers\Auth; use Helpers\Request; use Helpers\Response; use Repositories\AddressRepository;
final class AddressController
{
 private function validate(array $d): array { $e=[]; if(strlen($d['full_name']??'')<2||strlen($d['full_name']??'')>50)$e['full_name']='Full name must be 2-50 characters'; if(!preg_match('/^[0-9]{10}$/',$d['phone']??''))$e['phone']='Phone must be exactly 10 digits'; if(empty($d['address_line1'])||strlen($d['address_line1'])>100)$e['address_line1']='Address line 1 required max 100 chars'; foreach(['address_line2'=>100,'landmark'=>50] as $k=>$m) if(!empty($d[$k])&&strlen($d[$k])>$m)$e[$k]='Too long'; if(!preg_match('/^[0-9]{6}$/',$d['pincode']??''))$e['pincode']='PIN code must be 6 digits'; foreach(['city','state','country'] as $k) if(!preg_match('/^[A-Za-z ]+$/',$d[$k]??''))$e[$k]='Only alphabets and spaces allowed'; return $e; }
 public function index(): never { try{$u=Auth::requireUser(); Response::success((new AddressRepository())->all((int)$u['id']));}catch(\Throwable $e){Response::error($e->getMessage(),401);} }
 public function create(): never { try{$u=Auth::requireUser();$d=Request::input();$e=$this->validate($d); if($e)Response::error('Validation failed',422,$e); $r=new AddressRepository();$id=$r->create((int)$u['id'],$d); Response::success(['id'=>$id], 'Address saved',201);}catch(\Throwable $e){Response::error($e->getMessage(),400);} }
 public function update(string $id): never { try{$u=Auth::requireUser();$d=Request::input();$e=$this->validate($d); if($e)Response::error('Validation failed',422,$e); (new AddressRepository())->update((int)$u['id'],(int)$id,$d); Response::success([], 'Address updated');}catch(\Throwable $e){Response::error($e->getMessage(),400);} }
 public function delete(string $id): never { try{$u=Auth::requireUser();(new AddressRepository())->delete((int)$u['id'],(int)$id); Response::success([], 'Address deleted');}catch(\Throwable $e){Response::error($e->getMessage(),400);} }
 public function setDefault(string $id): never { try{$u=Auth::requireUser();(new AddressRepository())->setDefault((int)$u['id'],(int)$id); Response::success([], 'Default address updated');}catch(\Throwable $e){Response::error($e->getMessage(),400);} }
}
