<?php
include_once(__DIR__."/api-common.php");
include_once(__DIR__."/../my-optician-wsdl-service/MyOpticianWsdlService.php");
global $service_url, $optician_id;

//verifications
checkPost();
$postData = json_decode(file_get_contents('php://input'), true);
errorIfNotSet('appointment_slot', $postData);
errorIfNotSet('shop_name', $postData);
errorIfNotSet('practitioner_name', $postData);
errorIfNotSet('firstname', $postData);
errorIfNotSet('lastname', $postData);
errorIfNotSet('existing_patient', $postData);
errorIfNotSet('email', $postData);
errorIfNotSet('appointment_type', $postData);

$opticianService = new MyOpticianWsdlService($service_url, $optician_id);
// if(isset($postData['site_id']))
//     $siteId = $postData['site_id'];
// else{
    $siteInfo = $opticianService->getSiteInfo($optician_id, $password);
    $siteId = $siteInfo->getSite();
// }

$appointmentSlot = $postData['appointment_slot'];
$shopName = $postData['shop_name'];

// Assuming you have a form to collect appointment details
$existing = $postData['existing_patient']===true || strtolower($postData['existing_patient'])==='true' ? 'True' : 'False';
$appointmentDetails = new AppointmentDetails();
$appointmentDetails->setAppointmentType($postData['appointment_type']);
$appointmentDetails->setName($postData['firstname'] . ' ' . $postData['lastname']);
$appointmentDetails->setExisting( $existing);
$appointmentDetails->setEmail($postData['email']);
$appointmentDetails->setPractitioner($postData['practitioner_name']);
$appointmentDetails->setDob(isset($postData['dob']) ? $postData['dob'] : '');
$appointmentDetails->setPhone(isset($postData['mobile']) ? $postData['mobile'] : '');
$appointmentDetails->setPostcode(isset($postData['postcode']) ? $postData['postcode'] : '');
$appointmentDetails->setComments(isset($postData['comment']) ? $postData['comment'] : '');
// Assuming practitioner data is also present in the POST data

// Call the postNewAppointment method from your service
$result = $opticianService->postNewAppointment($siteId, $appointmentSlot, $appointmentDetails, $shopName, $siteInfo);

header('Content-Type: application/json');
// Check the result and return a JSON response
if ($result) {
    echo json_encode(['data' => [], 
    "status" => ["success"=>true, "message" => "Appointment is booked successfully", "code" => 200 ]]);
} else {
    echo json_encode(['data'=> [], 
    "status" => ["success"=>false, "message" => "Error in booking the appointment, please try again later.", "code" => 500 ]]);
}

?>