<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin','dentist','receptionist','staff','dental_assistant']);
require_once DENTAL_ROOT . '/app/transaction_integrity.php';
require_once DENTAL_ROOT . '/app/appointment_planning.php';

$pdo=db();
$returnTo='doctor_treatment.php';
$return=(string)($_POST['return']??'');
if($return!==''&&preg_match('/^(doctor_treatment|appointments|queue|inhouse_checkups)\.php(?:\?[A-Za-z0-9_=&%.-]*)?$/',$return))$returnTo=$return;

try{
    if($_SERVER['REQUEST_METHOD']!=='POST')throw new RuntimeException('This service action must be submitted from the active appointment.');
    verify_csrf();
    $segmentId=(int)($_POST['appointment_service_id']??0);
    $action=(string)($_POST['service_action']??'');
    $reason=trim((string)($_POST['reason']??''));
    $destinationId=(int)($_POST['destination_appointment_id']??0);
    if($segmentId<1)throw new RuntimeException('Select the planned service to update.');

    $context=appointment_service_disposition_context($pdo,$segmentId,false);
    $role=active_role();
    if($role==='dentist'){
        $assigned=(int)($context['dentist_user_id']??$context['appointment_dentist_user_id']??0);
        if($assigned>0&&$assigned!==(int)(current_user()['id']??0))throw new RuntimeException('Only the assigned Dentist may defer or move this Dentist service.');
    }
    if($role==='dental_assistant'){
        $scope=task_dentist_scope_ids();
        $assigned=(int)($context['dentist_user_id']??$context['appointment_dentist_user_id']??0);
        if($assigned>0&&!in_array($assigned,$scope,true))throw new RuntimeException('This service is outside the assistant’s assigned Dentist scope.');
    }

    $pdo->beginTransaction();
    $destination=appointment_apply_service_disposition($pdo,$segmentId,$action,$reason,$destinationId);
    $pdo->commit();
    $message=match($action){
        'move_existing'=>'Service moved to appointment #'.$destination.'.',
        'defer_next'=>'Service deferred and prioritized on appointment #'.$destination.'.',
        'create_followup'=>'Pending follow-up appointment #'.$destination.' created with the same Dentist when available.',
        default=>'Service marked not performed; the original appointment history was preserved.',
    };
    flash('success',$message);
}catch(Throwable $exception){
    if($pdo->inTransaction())$pdo->rollBack();
    flash('error',$exception->getMessage());
}
header('Location: '.$returnTo);
exit;
