<?php
declare(strict_types=1);
namespace Repositories;
final class AddressRepository extends BaseRepository
{
 public function all(int $uid): array { return $this->fetchAll('SELECT * FROM addresses WHERE user_id=:u ORDER BY is_default DESC, updated_at DESC',['u'=>$uid]); }
 public function create(int $uid,array $d): int { if(!empty($d['is_default']))$this->unsetDefault($uid); $this->execute('INSERT INTO addresses(user_id,full_name,phone,address_line1,address_line2,landmark,pincode,city,state,country,is_default) VALUES(:user_id,:full_name,:phone,:address_line1,:address_line2,:landmark,:pincode,:city,:state,:country,:is_default)', $this->map($uid,$d)); return (int)$this->db->lastInsertId(); }
 public function update(int $uid,int $id,array $d): void { if(!empty($d['is_default']))$this->unsetDefault($uid); $m=$this->map($uid,$d); $m['id']=$id; $this->execute('UPDATE addresses SET full_name=:full_name, phone=:phone, address_line1=:address_line1, address_line2=:address_line2, landmark=:landmark, pincode=:pincode, city=:city, state=:state, country=:country, is_default=:is_default WHERE id=:id AND user_id=:user_id',$m); }
 public function delete(int $uid,int $id): void { $this->execute('DELETE FROM addresses WHERE id=:id AND user_id=:u',['id'=>$id,'u'=>$uid]); }
 public function setDefault(int $uid,int $id): void { $this->db->beginTransaction(); $this->unsetDefault($uid); $this->execute('UPDATE addresses SET is_default=1 WHERE id=:id AND user_id=:u',['id'=>$id,'u'=>$uid]); $this->db->commit(); }
 public function find(int $uid,int $id): ?array { return $this->fetchOne('SELECT * FROM addresses WHERE id=:id AND user_id=:u LIMIT 1',['id'=>$id,'u'=>$uid]); }
 private function unsetDefault(int $uid): void { $this->execute('UPDATE addresses SET is_default=0 WHERE user_id=:u',['u'=>$uid]); }
 private function map(int $uid,array $d): array { return ['user_id'=>$uid,'full_name'=>$d['full_name'],'phone'=>$d['phone'],'address_line1'=>$d['address_line1'],'address_line2'=>$d['address_line2']??null,'landmark'=>$d['landmark']??null,'pincode'=>$d['pincode'],'city'=>$d['city'],'state'=>$d['state'],'country'=>$d['country']??'India','is_default'=>!empty($d['is_default'])?1:0]; }
}
