<?php
/**
 * Created by PhpStorm.
 * User: sunusi
 * Date: 2019-01-24
 * Time: 19:40
 */

session_start();

require_once getcwd() . "/../functions/db.class.php";
require_once getcwd() . "/../functions/form.data.php";
require_once getcwd() . "/../functions/robot.php";
require_once getcwd() . "/../functions/config.php";


if (isset($_POST["patientId"])) {

    //selecting the service type id
    $service_type =
        $conn->query("select * from udut_services_types where typeName = '".$_POST["typeId"]."' and serviceId = '".$_POST["serviceId"]."' ")
            ->fetch_assoc() or die("Error fetching services type ".$conn->error);
    /*
     * assigning value for adding service
     */
    $_POST['typeId'] = $service_type["typeId"];

    /*
     * adding other information to the array
     */
    $_POST["userId"] = $_SESSION["YUZA_ID"];
    $_POST["receiptNo"] = genReceiptNo();

    if(!empty($_FILES)){
        $SQLPayments = SQLStatement("udut_payments", $_POST);
        $PatientReferrals = move_files($_FILES, "patientReferralLetter", "../referral/");

        /*
         * Saving the payment details
         */
       $conn->query($SQLPayments) or die("Problem saving payment details ".$conn->error);


    }


    $payment = $conn->query("SELECT * FROM udut_payments ORDER BY paymentId DESC LIMIT 1")->fetch_assoc() or die("Problem fetching payments detail ".$conn->error);
    $paymentId = $payment['paymentId'];

    $visit = array("paymentId" => $paymentId, "patientId" => $_POST["patientId"]);
    $SQLVisits = SQLStatement("udut_visits", $visit);

    /*
    * Saving the visit details
    */
    $query->execute($SQLVisits) or die("Problem saving visit details ".$conn->error);

    //unset the sync information
    $conn->query("update udut_patients set patientSyncStatus = 0  where patientId = '".$_POST["patientId"]."' ");

    header("location: ../about-patient/" .$_POST["patientId"]);

} else {
    header("location: ../add-service/".$_POST["patientId"]);
}