<?php
/**
 * Created by PhpStorm.
 * User: sunusi
 * Date: 2019-03-01
 * Time: 14:48
 */

//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' ");
    $percentConfiguration = $db->getAll("select * from udut_configurations where configStatus = 1 and configType = '%' ");
    //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 = "";
    $percentRows = "";
    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>";
    }
    $totalMonthlyRevenueAfterFixedValues = $totalMonthlyRevenue;
    foreach ($percentConfiguration as $percentConfig) {
        $totalMonthlyRevenue = $totalMonthlyRevenueAfterFixedValues;
        $amount = ($percentConfig['configValue'] * $totalMonthlyRevenue) / 100;
        $percentRows =
            $percentRows . "<tr>
              <td>" . ucwords($percentConfig['configName']) . "</td>
              <td class='color-yellow'>" . $percentConfig['configType'] . "</td>
              <td>&#x20A6; " . number_format($amount) . " (" . $percentConfig['configValue'] . "% of &#x20A6;" . $totalMonthlyRevenueAfterFixedValues . ")</td>
              <td>" . $monthName . ", " . $m_y[0] . "</td>
            </tr>";
    }

    $totalRevenue =
        "<tr>
              <td>" . ucwords("Total") . "</td>
              <td class='color-yellow'> - </td>
              <td class='color-red'><strong>&#x20A6; " . number_format(getTotalMonthlyRevenue($month)) . "</strong></td>
            </tr>";

    $revenueTable = '
      
      <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 . '
            ' . $percentRows . '
            ' . $totalRevenue . '
          </tbody>
      </table>
    
    ';


    return $revenueTable;
}