<?php

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

try {
    $branchId=(int)($_GET['branch_id']??public_request_branch_id()??0);
    $doctorId=(int)($_GET['doctor_id']??0);
    $serviceId=(int)($_GET['service_id']??0);
    $serviceIds=array_filter(array_map('intval',explode(',',(string)($_GET['service_ids']??''))));
    if($serviceId>0)array_unshift($serviceIds,$serviceId);
    $serviceIds=array_values(array_unique($serviceIds));
    $horizon=max(14,min(180,(int)($_GET['horizon']??90)));
    $newPatient=(string)($_GET['patient_type']??'')==='new';
    $patientId=(int)($_GET['patient_id']??0);
    $limit=max(6,min(40,(int)($_GET['limit']??18)));
    if($branchId<1||!$serviceIds)throw new RuntimeException('Select at least one service first.');
    $services=appointment_service_definitions($branchId,$serviceIds);
    $providerModel=appointment_bundle_provider_model($services);
    $dates=[];
    for($offset=0;$offset<=$horizon&&count($dates)<$limit;$offset++){
        $date=date('Y-m-d',strtotime('today +'.$offset.' days'));
        if(!branch_hours_for_date($branchId,$date))continue;
        $options=appointment_bundle_available_options($branchId,$date,$services,$doctorId,$newPatient,0,$patientId);
        if(!$options)continue;
        $doctorSummaries=[];$seen=[];
        foreach($options as $option){
            $id=(int)$option['doctor_id'];
            if($id<1||isset($seen[$id]))continue;
            $seen[$id]=true;
            $doctorSummaries[]=['id'=>$id,'name'=>(string)$option['doctor_name'],'chair_name'=>(string)$option['chair_name'],'slot_count'=>count(array_filter($options,static fn(array $row):bool=>(int)$row['doctor_id']===$id))];
        }
        $dates[]=[
            'date'=>$date,
            'weekday'=>date('D',strtotime($date)),
            'day'=>date('j',strtotime($date)),
            'month'=>date('M',strtotime($date)),
            'label'=>date('D, M j',strtotime($date)),
            'slot_count'=>count($options),
            'first_time'=>(string)$options[0]['time'],
            'last_time'=>(string)$options[count($options)-1]['time'],
            'doctors'=>$doctorSummaries,
            'provider_type'=>$providerModel,
            'duration_minutes'=>(int)$options[0]['duration_minutes'],
        ];
    }
    $message=$dates
        ? 'Choose an available date for the complete service bundle, then select one of its coordinated times.'
        : 'No complete sequence is open for every selected service, provider, and chair within the search period.';
    echo json_encode(['ok'=>true,'dates'=>$dates,'message'=>$message,'service'=>$services[0],'services'=>$services,'provider_type'=>$providerModel],JSON_UNESCAPED_SLASHES);
}catch(Throwable $e){
    http_response_code(422);
    echo json_encode(['ok'=>false,'dates'=>[],'message'=>$e->getMessage()]);
}
