<?php
/**
 * Created by PhpStorm.
 * User: sunusi
 * Date: 11/21/2018
 * Time: 6:35 PM
 */


$query = new db();

function path()
{
    $path = str_replace("index.php", "", $_SERVER['PHP_SELF']);
    return $path;
}

/*
 * getting the configuration settings
 * from the database
 *
 */


$siteName = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'siteName' ");
$siteLogo = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'siteLogo' ");
$runningCost = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'runningCost' ");
$hosAccPer = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'HosAccPer' ");
$hosHosAccPer = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'hosHosAccPer' ");
$hosAdmFee = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'hosAdmFee' ");
$hosRadDep = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'hosRadDep' ");
$foresightPer = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'foresightPer' ");
$kalifaPer = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'kalifaPer' ");
$udutAddress = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'udutAddress' ");
$patternPatientUId = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'patternPatientUId' ");


if (isset($_SESSION['YUZA_ID'])) {
    $user = $query->getOne("SELECT * from udut_users WHERE userId = '" . $_SESSION['YUZA_ID'] . "'  ");
}

/*
 * safe input function
 */
function safe_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES);
    return $data;
}

/*
 * generate new id for student
 */
function genPatientUId()
{
    $query = new db();

    // generation patient configuration pattern
    $config = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'patternPatientUId' ");
    $pattern = $config["configValue"];

    // generating year
    $newyear = date("y");

    //padding the patient ID
    //selecting last patient number


    $qry = $query->getOne("SELECT * FROM udut_patients ORDER BY patientId DESC LIMIT 1");


    $patientUId = $qry['patientUId'];
    $genUID = explode("/", $patientUId);

    //check the year
    $currentyear = $genUID['1'];
    $patientId = $genUID['2'];

    $newyear = date("y");

    if ($newyear == $currentyear) {
        $year = $currentyear;
    } else {
        $year = $newyear;
        $patientId = 0;
    }

    $patientId = $patientId + 1;
    $patientId = str_pad($patientId, 4, "0", STR_PAD_LEFT);

    // concatenate
    $patientUId = $pattern . '/' . $year . '/' . $patientId;

    return $patientUId;
}

/*
 * Generating receipt number
 */
function genReceiptNo()
{
    $query = new db();
    //padding the patient ID
    //selecting last patient number
    $qry = $query->getOne("SELECT * FROM udut_payments ORDER BY paymentId DESC LIMIT 1");
    $paymentId = $qry['paymentId'];
    $paymentId = $paymentId + 1;
    $receiptNo = str_pad($paymentId, 7, "0", STR_PAD_LEFT);

    return $receiptNo;
}

/*
 * Function to Convert $_POST in to SQL statement
 * and return for insert function
 */
function SQLStatement($table, $data)
{
    $table = '`' . $table . '`';
    // variable declaration
    $columns = "";
    $values = "";

    // loop
    foreach ($data as $column => $value) {
        $columns = $columns . ', `' . safe_input((string)$column) . '`';
        $values = $values . ',\'' . safe_input((string)$value) . '\'';
    }

    // trimming the first comma from the result above
    $columns = ltrim($columns, ',');
    $values = ltrim($values, ',');

    // statement
    $sql = "INSERT INTO ${table} ( ${columns} ) VALUES ( ${values} )";

    return $sql;
}

/*
 * Function to Convert $_POST in to SQL statement
 * and return for insert function
 */
function SQLStmtUpdate($table, $data, $condition)
{
    $table = '`' . $table . '`';

    // variable declaration
    $columns = "";
    $values = "";

    // loop
    foreach ($data as $column => $value) {
        $values = $values . ", `" . $column . "` = '" . $value . "'";
    }

    // trimming the first comma from the result above
    $values = ltrim($values, ',');

    // statement
    $sql = "UPDATE ${table} SET ( ${values} ) WHERE ${condition}";

    return $sql;
}

/*
 * Function to move any file to a specific directory
 */
function move_files($arr_files, $filename, $location)
{
    if (isset($arr_files[$filename])) {
        $errors = array();
        $uploads_dir = $location;
        $file_name = $arr_files[$filename]['name'];
        $file_size = $arr_files[$filename]['size'];
        $file_tmp = $arr_files[$filename]['tmp_name'];
        $file_type = $arr_files[$filename]['type'];
        $file_ext_temp = explode('.', $arr_files[$filename]['name']);
        $file_ext = strtolower(end($file_ext_temp));

        $extensions = array("jpeg", "jpg", "png");

        if (in_array($file_ext, $extensions) === false) {
            $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
        }

        if ($file_size > 2097152) {
            $errors[] = 'File size must be excately 2 MB';
        }

        if (empty($errors) == true) {
            move_uploaded_file($file_tmp, $location . $file_name);
            return $file_name;
        } else {
            print_r($errors);
        }

    } else {
        echo "no such file exist";
    }


}

/*
 * time elapse function
 */
date_default_timezone_set('Africa/Lagos');
function time_elapsed_string($datetime, $full = false)
{
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}


function genMonthlyRevenue()
{
    //database object
    $query = new db();
}

//generate config functions based on the configuration name from the database
function getConfig($configName)
{
    $query = new db();
    $config = $query->getOne("
      SELECT * 
      FROM udut_configurations 
      WHERE configName = '" . $configName . "'
    ");
    $configValue = $config["configValue"];
    return $configValue;
}

//generate the total monthly revenue to be used in the ppp sharing formula
function getTotalMonthlyRevenue($month)
{
    $query = new db();
    //fetch revenue according to month
    $sql = $query->getAll("
        SELECT udut_payments.*,
               udut_scan_types.*
        FROM udut_payments
        JOIN udut_scan_types
        ON udut_payments.typeId = udut_scan_types.typeId
        WHERE udut_payments.paymentDateAdded LIKE '%" . $month . "%'
    ");
    $totalAmount = 0;
    foreach ($sql as $revenue) {
        $totalAmount = $totalAmount + $revenue['typeAmount'];
    }
    return $totalAmount;
}

//generate total monthly revenue after removing the fixed running cost
function getTotalAfterRunningCost($month)
{
    $runningCost = getConfig("runningCost");
    $totalRevenue = getTotalMonthlyRevenue($month);
    $afterRunningCost = $totalRevenue - $runningCost;
    return $afterRunningCost;
}

//generate hospital percentage from function getTotalAfterRunningCost()
function getHospitalPercentage($month)
{
    $hospitalPercentage = getConfig("hosAccPer");
    $totalRevenue = getTotalAfterRunningCost($month);
    $hospitalRevenue = ($hospitalPercentage * $totalRevenue) / 100;
    return $hospitalRevenue;
}

//generate management percentage from function getTotalAfterRunningCost()
function getManagementPercentage($month)
{
    $managementPercentage = getConfig("manAccPer");
    $totalRevenue = getTotalAfterRunningCost($month);
    $managementRevenue = ($managementPercentage * $totalRevenue) / 100;
    return $managementRevenue;
}

//generate total revenue after deducting hospital and management percentage
function getTotalAfterHnMPercentage($month)
{
    $hospitalPercentage = getHospitalPercentage($month);
    $managementPercentage = getManagementPercentage($month);
    $deducted = $hospitalPercentage + $managementPercentage;
    $totalRevenue = getTotalAfterRunningCost($month) - $deducted;
    return $totalRevenue;
}

//generate foresight percentage after hospital and management percentage
function getForesightPercentage($month)
{
    $foresightPercentage = getConfig("foresightPer");
    $afterHnM = getTotalAfterHnMPercentage($month);
    $totalRevenue = ($foresightPercentage * $afterHnM) / 100;
    return $totalRevenue;
}

//generate kalifa percentage as remaining percent of the foresight
function getKalifaPercentage($month)
{
    $kalifaPercentage = getConfig("kalifaPer");
    $afterHnM = getTotalAfterHnMPercentage($month);
    $totalRevenue = ($kalifaPercentage * $afterHnM) / 100;
    return $totalRevenue;
}

//splitting hospital 30% percentage into the following functions
//generate hospital account percentage
function getHospitalAccountPercentage($month)
{
    $hospitalAccount = getConfig("hosHosAccPer");
    $hospitalPercentage = getTotalAfterRunningCost($month);
    $totalRevenue = ($hospitalAccount * $hospitalPercentage) / 100;
    return $totalRevenue;
}

//generate administration fee
function getAdministrationFeePercentage($month)
{
    $administrationFee = getConfig("hosAdmFee");
    $hospitalPercentage = getTotalAfterRunningCost($month);
    $totalRevenue = ($administrationFee * $hospitalPercentage) / 100;
    return $totalRevenue;
}

//generate CMD percentage
function getCMDPercentage($month)
{
    $hospitalCMD = getConfig("hosCMD");
    $hospitalPercentage = getTotalAfterRunningCost($month);
    $totalRevenue = ($hospitalCMD * $hospitalPercentage) / 100;
    return $totalRevenue;
}

//generate Dr. Admin percentage
function getDrAdminPercentage($month)
{
    $hospitalDrAdmin = getConfig("hosDrAdm");
    $hospitalPercentage = getTotalAfterRunningCost($month);
    $totalRevenue = ($hospitalDrAdmin * $hospitalPercentage) / 100;
    return $totalRevenue;
}

//generate radiology department percentage
function getRadiologyDepartmentPercentage($month)
{
    $hospitalRadiologyDepartment = getConfig("hosRadDep");
    $hospitalPercentage = getTotalAfterRunningCost($month);
    $totalRevenue = ($hospitalRadiologyDepartment * $hospitalPercentage) / 100;
    return $totalRevenue;
}

