<?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' ");
$khalifaPer = $query->getOne("SELECT * FROM udut_configurations WHERE configName = 'khalifaPer' ");
$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);

    //user id
    $userId = "";
    $userId = $_SESSION['YUZA_ID'];

    //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 . $userId . '/' . $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';
}


/*
 * check if there is internet connection
 */

function is_connected()
{
    $connected = @fsockopen("www.uduthctppp.com", 80);
    //website, port  (try 80 or 443)
    if ($connected) {
        $is_conn = true; //action when connected
        fclose($connected);
    } else {
        $is_conn = false; //action in connection failure
    }
    return $is_conn;

}


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_services_types.*
        FROM udut_payments
        JOIN udut_services_types
        ON udut_payments.typeId = udut_services_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 uduth percentage from function getTotalAfterRunningCost()
function getuduthPercentage($month)
{
    $uduthPercentage = getConfig("hosAccPer");
    $totalRevenue = getTotalAfterRunningCost($month);
    $uduthRevenue = ($uduthPercentage * $totalRevenue) / 100;
    return $uduthRevenue;
}

//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 uduth and management percentage
function getTotalAfterHnMPercentage($month)
{
    $uduthPercentage = getuduthPercentage($month);
    $managementPercentage = getManagementPercentage($month);
    $deducted = $uduthPercentage + $managementPercentage;
    $totalRevenue = getTotalAfterRunningCost($month) - $deducted;
    return $totalRevenue;
}

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

//generate khalifa percentage as remaining percent of the foresight
function getkhalifaPercentage($month)
{
    $khalifaPercentage = getConfig("khalifaPer");
    $afterHnM = getTotalAfterHnMPercentage($month);
    $totalRevenue = ($khalifaPercentage * $afterHnM) / 100;
    return $totalRevenue;
}

//splitting uduth 30% percentage into the following functions
//generate uduth account percentage
function getuduthAccountPercentage($month)
{
    $uduthAccount = getConfig("hosHosAccPer");
    $uduthPercentage = getTotalAfterRunningCost($month);
    $totalRevenue = ($uduthAccount * $uduthPercentage) / 100;
    return $totalRevenue;
}

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

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

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

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

function revenueuduth()
{
    $db = new db();
    $uduth = $db->getOne("select * from udut_configurations where configName like '%uduth%' and configStatus = 1 and configType = '#1' ");
    return $uduth["configValue"];
}


//revenue formula
function calculateRevenue($month)
{
    $db = new db();

    //fetching all the active configuration record in the database
    $fixedConfiguration = $db->getAll("select * from udut_configurations where configStatus = 1 and configType = 'Fixed' ");
    $percent1Configuration = $db->getAll("select * from udut_configurations where configStatus = 1 and configType = '#1' ");
    $percent2Configuration = $db->getAll("select * from udut_configurations where configStatus = 1 and configType = '#2' ");
    $percent3Configuration = $db->getAll("select * from udut_configurations where configStatus = 1 and configType = '#3' ");
    $percent4Configuration = $db->getAll("select * from udut_configurations where configStatus = 1 and configType = '#4' ");
    $percent5Configuration = $db->getAll("select * from udut_configurations where configStatus = 1 and configType = '#5' ");
    $fixedPercentConfiguration = $db->getAll("select * from udut_configurations where configStatus = 1 and configType = 'Fixed%' ");

    //getting the full month
    $m_y = explode("-", $month);
    $monthNum = $m_y[1];
    $dateObj = DateTime::createFromFormat('!m', $monthNum);
    $monthName = $dateObj->format('F'); // March

    //deduct all fixed amounts
    $totalMonthlyRevenue = getTotalMonthlyRevenue($month);
    $fixedRows = "";
    $percent1Rows = "";
    $percent2Rows = "";
    $percent3Rows = "";
    $percent4Rows = "";
    $percent5Rows = "";
    $percentuduth = "";
    $fixedPercentRows = "";
    $totalPercent1 = 0;
    $totalPercent2 = 0;
    $totalPercent3 = 0;
    $totalPercent4 = 0;
    $totalPercent5 = 0;
    foreach ($fixedConfiguration as $fixedConfig) {
        $totalMonthlyRevenue = ($totalMonthlyRevenue - $fixedConfig['configValue']);
        $fixedRows =
            $fixedRows . "<tr>
              <td>" . ucwords($fixedConfig['configName']) . "</td>
              <td class='color-yellow'>" . $fixedConfig['configType'] . "</td>
              <td>&#x20A6; " . number_format($fixedConfig['configValue']) . " (Fixed)</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>";
//        print($config['configName'] . " = " . $config['configValue'] . "<br>");
    }
    foreach ($fixedPercentConfiguration as $fixedPercentConfig) {
        $amount = ($fixedPercentConfig['configValue'] * $totalMonthlyRevenue) / 100;
        $fixedPercentRows =
            $fixedPercentRows . "<tr>
              <td>" . ucwords($fixedPercentConfig['configName']) . "</td>
              <td class='color-yellow'>" . $fixedPercentConfig['configType'] . "</td>
              <td>&#x20A6; " . number_format($amount) . " (Fixed & %)</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>";
//        print($config['configName'] . " = " . $config['configValue'] . "<br>");
        $totalMonthlyRevenue = ($totalMonthlyRevenue - $amount);
    }

    if ($_SESSION["YUZA_NAME"] == "uduth" || $_SESSION["YUZA_NAME"] == "uduth") {
        $uduthAcc = revenueuduth();
        $totalMonthlyRevenueAfterFixedValues1 = $totalMonthlyRevenue;
        $uduthAcc = ($uduthAcc * $totalMonthlyRevenueAfterFixedValues1) / 100;


        $percentuduth = "<tr>
              <td>uduth</td>
              <td class='color-yellow'> 1 % </td>
              <td>&#x20A6; " . number_format($uduthAcc) . " (" . revenueuduth() . "%)</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>
        ";
        $totalMonthlyRevenueAfterFixedValues1 = $totalMonthlyRevenueAfterFixedValues1 - $uduthAcc;
    } else {
        $totalMonthlyRevenueAfterFixedValues1 = $totalMonthlyRevenue;
    }

    foreach ($percent1Configuration as $percent1Config) {
        $amount = ($percent1Config['configValue'] * $totalMonthlyRevenueAfterFixedValues1) / 100;
        $percent1Rows =
            $percent1Rows . "<tr>
              <td>" . ucwords($percent1Config['configName']) . "</td>
              <td class='color-yellow'>" . $percent1Config['configType'] . "</td>
              <td>&#x20A6; " . number_format($amount) . " (" . $percent1Config['configValue'] . "% of " . number_format($totalMonthlyRevenueAfterFixedValues1) . "%)</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>";
        $totalMonthlyRevenue = ($totalMonthlyRevenue - $amount);
        $totalPercent1 = $totalPercent1 + $percent1Config['configValue'];
    }
    //    $totalPercent1 = 100 - $totalPercent1;
    $totalMonthlyRevenueAfterFixedValues2 = $totalMonthlyRevenue;
    foreach ($percent2Configuration as $percent2Config) {
        $amount = ($percent2Config['configValue'] * $totalMonthlyRevenueAfterFixedValues2) / 100;
        $percent2Rows =
            $percent2Rows . "<tr>
              <td>" . ucwords($percent2Config['configName']) . "</td>
              <td class='color-yellow'>" . $percent2Config['configType'] . "</td>
              <td>&#x20A6; " . number_format($amount) . " (" . $percent2Config['configValue'] . "% of " . number_format($totalMonthlyRevenueAfterFixedValues2) . "%)</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>";
        $totalMonthlyRevenue = ($totalMonthlyRevenue - $amount);
        $totalPercent2 = $totalPercent2 + $percent2Config['configValue'];
    }

    $totalMonthlyRevenueAfterFixedValues3 = $totalMonthlyRevenue;
    foreach ($percent3Configuration as $percent3Config) {
        $amount = ($percent3Config['configValue'] * $totalMonthlyRevenueAfterFixedValues3) / 100;
        $percent3Rows =
            $percent3Rows . "<tr>
              <td>" . ucwords($percent3Config['configName']) . "</td>
              <td class='color-yellow'>" . $percent3Config['configType'] . "</td>
              <td>&#x20A6; " . number_format($amount) . " (" . $percent3Config['configValue'] . "% of " . number_format($totalMonthlyRevenueAfterFixedValues3) . "%)</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>";
        $totalMonthlyRevenue = ($totalMonthlyRevenue - $amount);
        $totalPercent3 = $totalPercent3 + $percent3Config['configValue'];
    }

    $totalMonthlyRevenueAfterFixedValues4 = $totalMonthlyRevenue;
    foreach ($percent4Configuration as $percent4Config) {
        $amount = ($percent4Config['configValue'] * $totalMonthlyRevenueAfterFixedValues4) / 100;
        $percent4Rows =
            $percent4Rows . "<tr>
              <td>" . ucwords($percent4Config['configName']) . "</td>
              <td class='color-yellow'>" . $percent4Config['configType'] . "</td>
              <td>&#x20A6; " . number_format($amount) . " (" . $percent4Config['configValue'] . "% of " . number_format($totalMonthlyRevenueAfterFixedValues4) . "%)</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>";
        $totalMonthlyRevenue = ($totalMonthlyRevenue - $amount);
        $totalPercent4 = $totalPercent4 + $percent4Config['configValue'];
    }

    $totalMonthlyRevenueAfterFixedValues5 = $totalMonthlyRevenue;
    foreach ($percent5Configuration as $percent5Config) {
        $amount = ($percent5Config['configValue'] * $totalMonthlyRevenueAfterFixedValues5) / 100;
        $percent5Rows =
            $percent5Rows . "<tr>
              <td>" . ucwords($percent5Config['configName']) . "</td>
              <td class='color-yellow'>" . $percent5Config['configType'] . "</td>
              <td>&#x20A6; " . number_format($amount) . " (" . $percent5Config['configValue'] . "% of " . number_format($totalMonthlyRevenueAfterFixedValues5) . "%)</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>";
        $totalMonthlyRevenue = ($totalMonthlyRevenue - $amount);
        $totalPercent5 = $totalPercent5 + $percent5Config['configValue'];
    }

    $totalRevenue =
        "<tr>
              <td>" . ucwords("Total") . "</td>
              <td class='color-yellow'> - </td>
              <td class='color-red'><strong>&#x20A6; " . number_format(getTotalMonthlyRevenue($month)) . "</strong></td>
            </tr>";
//    echo $totalMonthlyRevenueAfterFixedValues;
    //getting the percentage value
    $revenueTablekhalifa = '
      <table class="table" width="100%" class="table table-condensed table-bordered">
          <thead>
            <tr>
              <th>Names</th>
              <th>Types</th>
              <th>Amount (Fixed / Percent)</th>
              <th>Month</th>
            </tr>
          </thead>
          <tbody>
            ' . $fixedRows . '
            ' . $fixedPercentRows . '
            ' . $percent1Rows . '
            ' . $percent2Rows . '
            ' . $percent3Rows . '
            ' . $percent4Rows . '
            ' . $percent5Rows . '
            ' . $totalRevenue . '
          </tbody>
      </table>
    ';

    $revenueTableForesight = '
      <table class="table" width="100%" class="table table-condensed table-bordered">
          <thead>
            <tr>
              <th>Names</th>
              <th>Types</th>
              <th>Amount (Fixed / Percent)</th>
              <th>Month</th>
            </tr>
          </thead>
          <tbody>
            ' . $fixedRows . '
            ' . $fixedPercentRows . '
            ' . $percent1Rows . '
            ' . $percent2Rows . '
            ' . $percent3Rows . '
            ' . $percent4Rows . '
            ' . $percent5Rows . '
            ' . $totalRevenue . '
          </tbody>
      </table>
    ';

    $revenueTableuduth = '
      <table class="table" width="100%" class="table table-condensed table-bordered">
          <thead>
            <tr>
              <th>Names</th>
              <th>Types</th>
              <th>Amount (Fixed / Percent)</th>
              <th>Month</th>
            </tr>
          </thead>
          <tbody>

            ' . $percentuduth . '

          </tbody>
      </table>
    ';


    $sysUsers = $db->getOne("
                  SELECT udut_users.*,
                         udut_users_roles.*
                  FROM udut_users 
                  JOIN udut_users_roles
                  ON udut_users.userId = udut_users_roles.userId
                  WHERE udut_users.userId = '" . $_SESSION['YUZA_ID'] . "'
                ");
    if ($sysUsers["userUsername"] == "khalifa") {
        return $revenueTablekhalifa;
    }
    if ($sysUsers["userUsername"] == "uduth") {
        return $revenueTableuduth;
    }
    if ($sysUsers["userUsername"] == "foresight") {
        return $revenueTableForesight;
    } else {
        return "This user is not allowed to view the revenue page.";
    }

}


function getPatientsDetails()
{
    global $conn;
    $query = $conn->query("
      SELECT udut_patients.*
      FROM udut_patients    
      WHERE udut_patients.patientSyncStatus = 0;
    ") or die("Error fetching patients information " . $conn->error);
    //converting the array
    return $query;
}

function getPaymentsDetails($patientId)
{
    global $conn;
    $query = $conn->query("
      SELECT udut_payments.*
      FROM udut_payments    
      WHERE udut_payments.patientId = '${patientId}' ;
    ") or die("Error fetching patients information " . $conn->error);
    return $query;
}

function getReportsDetailsByUserId($userId)
{
    global $conn;
    $query = $conn->query("
        SELECT udut_reports.*
        FROM udut_reports 
        WHERE udut_reports.userId = '${userId}' and udut_reports.reportSyncStatus = 0
    ") or die("Error fetching reports details " . $conn->error);
    return $query;
}
