<?php
declare(strict_types=1);
namespace App\Repositories;
use App\Core\Database;
final class AppointmentRepository {
 public function list(array $filters,?int $therapistId=null):array { $where=['1=1'];$params=[];$mode=(string)($filters['view']??'week');$date=(string)($filters['date']??date('Y-m-d'));if(!preg_match('/^\d{4}-\d{2}-\d{2}$/',$date))$date=date('Y-m-d');if($mode==='day'){$where[]='a.appointment_date=:date';$params['date']=$date;}elseif($mode==='month'){$where[]='a.appointment_date>=:month_start AND a.appointment_date<:month_end';$params['month_start']=date('Y-m-01',strtotime($date));$params['month_end']=date('Y-m-01',strtotime($date.' +1 month'));}else{$monday=date('Y-m-d',strtotime('monday this week',strtotime($date)));$where[]='a.appointment_date BETWEEN :week_start AND :week_end';$params['week_start']=$monday;$params['week_end']=date('Y-m-d',strtotime($monday.' +6 days'));}if($therapistId!==null){$where[]='a.therapist_id=:therapist_id';$params['therapist_id']=$therapistId;}if(($filters['status']??'')!==''){$where[]='a.status=:status';$params['status']=$filters['status'];}$stmt=Database::connection()->prepare('SELECT a.*,p.patient_reference,p.first_name,p.last_name,u.full_name AS therapist_name,sv.name AS service_name,sv.price AS service_price FROM appointments a INNER JOIN patients p ON p.id=a.patient_id INNER JOIN therapists t ON t.id=a.therapist_id INNER JOIN users u ON u.id=t.user_id LEFT JOIN services sv ON sv.id=a.service_id WHERE '.implode(' AND ',$where).' ORDER BY a.appointment_date ASC,a.start_time ASC,a.id ASC');$stmt->execute($params);return $stmt->fetchAll(); }
 public function find(int $id):?array{$stmt=Database::connection()->prepare('SELECT a.*,p.patient_reference,p.first_name,p.last_name,u.full_name AS therapist_name,sv.name AS service_name FROM appointments a INNER JOIN patients p ON p.id=a.patient_id INNER JOIN therapists t ON t.id=a.therapist_id INNER JOIN users u ON u.id=t.user_id LEFT JOIN services sv ON sv.id=a.service_id WHERE a.id=:id LIMIT 1');$stmt->execute(['id'=>$id]);$r=$stmt->fetch();return is_array($r)?$r:null;}
 public function create(array $d):int{$s=Database::connection()->prepare('INSERT INTO appointments (patient_id,therapist_id,service_id,appointment_date,start_time,end_time,status,notes,created_by) VALUES (:patient_id,:therapist_id,:service_id,:appointment_date,:start_time,:end_time,:status,:notes,:created_by)');$s->execute($d);return(int)Database::connection()->lastInsertId();}
 public function update(int $id,array $d):void{$d['id']=$id;$s=Database::connection()->prepare('UPDATE appointments SET patient_id=:patient_id,therapist_id=:therapist_id,service_id=:service_id,appointment_date=:appointment_date,start_time=:start_time,end_time=:end_time,status=:status,notes=:notes,updated_at=NOW() WHERE id=:id');$s->execute($d);}
 public function markCompleted(int $id,int $sessionId):void{$s=Database::connection()->prepare('UPDATE appointments SET status="completed",session_id=:session_id,updated_at=NOW() WHERE id=:id');$s->execute(['id'=>$id,'session_id'=>$sessionId]);}
 public function patients():array{return Database::connection()->query("SELECT id,patient_reference,first_name,last_name FROM patients WHERE deleted_at IS NULL AND status='active' ORDER BY last_name,first_name")->fetchAll();}
 public function patientsForTherapist(int $tid):array{$s=Database::connection()->prepare("SELECT DISTINCT p.id,p.patient_reference,p.first_name,p.last_name FROM patients p INNER JOIN patient_assignments pa ON pa.patient_id=p.id WHERE pa.therapist_id=:therapist_id AND pa.status='active' AND pa.ended_at IS NULL AND p.deleted_at IS NULL AND p.status='active' ORDER BY p.last_name,p.first_name");$s->execute(['therapist_id'=>$tid]);return$s->fetchAll();}
 public function therapists():array{return Database::connection()->query("SELECT t.id,u.full_name,t.professional_title FROM therapists t INNER JOIN users u ON u.id=t.user_id WHERE t.status='active' AND u.status='active' ORDER BY u.full_name")->fetchAll();}
 public function services():array{return Database::connection()->query("SELECT id,name,price FROM services WHERE status='active' ORDER BY name")->fetchAll();}
 public function activeAssignment(int $patientId,int $therapistId):?array{$s=Database::connection()->prepare('SELECT id,assigned_at FROM patient_assignments WHERE patient_id=:patient_id AND therapist_id=:therapist_id AND status="active" AND ended_at IS NULL ORDER BY assigned_at DESC,id DESC LIMIT 1');$s->execute(['patient_id'=>$patientId,'therapist_id'=>$therapistId]);$r=$s->fetch();return is_array($r)?$r:null;}
}
