<?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";


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

    $query = new db();
    /*
     * adding other information to the array
     */
    $_POST["patientUId"] = genPatientUId();
    $_POST["userId"] = $_SESSION["YUZA_ID"];


    /*
     * assigning value for adding service
     */
    $typeId = $_POST['typeId'];
    $paymentTypeId = $_POST['paymentTypeId'];
    $paymentStatusId = $_POST['paymentStatusId'];

    /*
     * unset unrelated array content
     */
    unset($_POST['typeId']);
    unset($_POST['paymentTypeId']);
    unset($_POST['paymentStatusId']);

    //creating SQL statement from file
    $SQLPatients = SQLStatement("udut_patients", $_POST);

    /*
     * Saving the patient details
     */
    if (!$query->execute($SQLPatients)) {
        echo "Problem saving patient details <br>";
    }

    /*
     * detect the recent patient details
     */
    $patient = $query->getOne("select * from udut_patients where patientUId = '" . $_POST["patientUId"] . "' ");

    //generating array for payments and visits
    $payments = array(
        "typeId" => $typeId,
        "paymentTypeId" => $paymentTypeId,
        "paymentStatusId" => $paymentStatusId,
        "userId" => $_SESSION["YUZA_ID"],
        "receiptNo" => genReceiptNo(),
        "patientId" => $patient['patientId']
    );

    $SQLPayments = SQLStatement("udut_payments", $payments);

    // Saving the payment details
    if (!$query->execute($SQLPayments)) {
        echo "Problem saving payment details <br>";
    }

    //selecting payment details
    $payment = $query->getOne("SELECT * FROM udut_payments ORDER BY paymentId DESC LIMIT 1");
    $paymentId = $payment['paymentId'];

    $visit = array(
        "paymentId" => $paymentId,
        "patientId" => $patient["patientId"]
    );

    $SQLVisits = SQLStatement("udut_visits", $visit);
    /*
    * Saving the visit details
    */
    if (!$query->execute($SQLVisits)) {
        echo "Problem saving visit details <br>";
    }

    //moving referral letter to referral folder
    $PatientReferrals = move_files($_FILES, "patientReferralLetter", "../referral/");

    /*
     * setting students array
     * normalize the array data and fetch sql statement
     */

    $Referral = array("patientId" => $patient['patientId'], "referralDoc" => $PatientReferrals);
    $SQLPatientReferrals = SQLStatement("udut_patients_referral_docs", $Referral);

    if (!$query->execute($SQLPatientReferrals)) {
        echo "Problem Saving referral Paper <br>";
    }

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

} else {
    header("location: ../add-patient");
}