<?php

declare(strict_types=1);
require dirname(__DIR__) . '/app/bootstrap.php';
require_once dirname(__DIR__) . '/app/appointment_planning.php';
header('Content-Type: application/json; charset=utf-8');

if (!current_user()) {
    http_response_code(401);
    echo json_encode(['ok'=>false,'appointments'=>[],'message'=>'Your session has expired. Sign in again.']);
    exit;
}
if (!can('patients.view',['super_admin','clinic_admin','receptionist','staff','dentist','dental_assistant','cashier'])) {
    http_response_code(403);
    echo json_encode(['ok'=>false,'appointments'=>[],'message'=>'Your role cannot view this patient schedule.']);
    exit;
}

try {
    $patientId=(int)($_GET['patient_id']??0);
    if($patientId<1) throw new RuntimeException('Select a patient first.');
    $pdo=db();
    $user=current_user()??[];
    $branchId=(int)($user['branch_id']??0);
    $patientStmt=$pdo->prepare('SELECT id FROM `' . table('patients') . '` WHERE id=? AND deleted_at IS NULL' . ($branchId>0?' AND branch_id=?':'') . ' LIMIT 1');
    $patientStmt->execute($branchId>0?[$patientId,$branchId]:[$patientId]);
    if(!$patientStmt->fetchColumn()) throw new RuntimeException('The selected patient is not available in this clinic branch.');
    [$scopeSql,$scopeArgs]=task_patient_scope_condition('a.patient_id');
    $sql='SELECT a.id,a.start_at,a.end_at,a.service_name,a.status,a.dentist_name,a.inhouse_provider_name,a.provider_type,a.series_id,a.series_sequence,a.planned_visit_label,s.series_name '
        .'FROM `' . table('appointments') . '` a LEFT JOIN `' . table('appointment_series') . '` s ON s.id=a.series_id '
        .'WHERE a.patient_id=? AND a.start_at>=NOW() AND a.status NOT IN ("cancelled","no_show","completed")' . ($branchId>0?' AND a.branch_id=?':'') . $scopeSql
        .' ORDER BY a.start_at LIMIT 12';
    $args=[$patientId];if($branchId>0)$args[]=$branchId;$args=array_merge($args,$scopeArgs);
    $stmt=$pdo->prepare($sql);$stmt->execute($args);$rows=$stmt->fetchAll();
    $services=appointment_services_for_ids($pdo,array_map(static fn(array $row):int=>(int)$row['id'],$rows));
    $appointments=[];
    foreach($rows as $row){
        $segments=[];
        foreach($services[(int)$row['id']]??[] as $service){
            $segments[]=[
                'name'=>(string)$service['service_name'],
                'start_at'=>(string)$service['start_at'],
                'end_at'=>(string)$service['end_at'],
                'provider'=>(string)($service['provider_type']==='inhouse'?($service['inhouse_provider_name']?:'Clinic team'):($service['dentist_name']?:'Dentist')),
            ];
        }
        $appointments[]=[
            'id'=>(int)$row['id'],
            'start_at'=>(string)$row['start_at'],
            'end_at'=>(string)$row['end_at'],
            'service_name'=>(string)$row['service_name'],
            'status'=>(string)$row['status'],
            'provider'=>(string)($row['provider_type']==='inhouse'?($row['inhouse_provider_name']?:'Clinic team'):($row['dentist_name']?:'Dentist')),
            'series_id'=>(int)($row['series_id']??0),
            'series_name'=>(string)($row['series_name']??''),
            'series_sequence'=>(int)($row['series_sequence']??0),
            'visit_label'=>(string)($row['planned_visit_label']??''),
            'segments'=>$segments,
            'edit_url'=>'appointments.php?edit_id='.(int)$row['id'],
        ];
    }
    echo json_encode(['ok'=>true,'appointments'=>$appointments,'message'=>$appointments?'':'No future appointments are currently booked.'],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}catch(Throwable $exception){
    http_response_code(422);
    echo json_encode(['ok'=>false,'appointments'=>[],'message'=>$exception->getMessage()],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
