<?

function calculate_horizontal_cylinder_volume($radius, $liquid_level_from_top, $length)
{

    $Step_1 = pi() * pow($radius, 2);
    $Step_2 = pow($radius, 2) * acos(($radius - $liquid_level_from_top) / $radius);
    $Step_3 = ($radius - $liquid_level_from_top) * sqrt((2 * $radius * $liquid_level_from_top) - pow($liquid_level_from_top, 2));
    $liquid_inside = round((($Step_1 - $Step_2 + $Step_3) * $length) / 1000000);
    $total_volume = round((pi() * pow($radius, 2) * $length) / 1000000);
    $percentage_filled = ($liquid_inside / $total_volume) * 100;
    return array(
        'fluid_volume_liters' => round($liquid_inside),
        'total_volume_liters' => round($total_volume),
        'percentage_filled' => round($percentage_filled)
    );
}


function calculate_horizontal_oval_tank_volume($radius1_mm, $radius2_mm, $depth_mm, $tank_length_mm)
{
    // Convert measurements to meters
    $radius1 = $radius1_mm / 1000; // Convert millimeters to meters
    $radius2 = $radius2_mm / 1000; // Convert millimeters to meters
    $depth = $depth_mm / 1000; // Convert millimeters to meters
    $tank_length = $tank_length_mm / 1000; // Convert millimeters to meters

    // Calculate the angle of the segment
    $theta = acos((($radius1 - $depth) / $radius1));

    // Calculate the volume of the fluid
    $volume_fluid = ($theta * $radius1 * $radius2) * $tank_length;

    // Convert volume to liters
    $volume_fluid_liters = $volume_fluid * 1000; // Convert cubic meters to liters

    // Calculate the total volume of the tank
    $volume_total = (M_PI * $radius1 * $radius2) * $tank_length;

    // Convert volumes to liters
    $volume_total_liters = $volume_total * 1000; // Convert cubic meters to liters

    // Calculate the percentage of the tank filled
    $percentage_filled = ($volume_fluid_liters / $volume_total_liters) * 100;

    return array(
        'fluid_volume_liters' => round($volume_fluid_liters),
        'total_volume_liters' => round($volume_total_liters),
        'percentage_filled' => round($percentage_filled)
    );
}

include "db.class.php";

$db = new db();

$date_5min_ago = date('Y-m-d H:i', strtotime("+ 115 Minutes"));
$date_now = date('Y-m-d H:i', strtotime("+ 120 Minutes"));

if (isset($_GET['username'])) {
    if (isset($_GET['password'])) {
        $login = $db->exec_query('users', ['*'], '', '', '', '', "username = '{$_GET['username']}' AND password = '{$_GET['password']}' AND status = 'ACTIVE'");
        if ($login->num_rows == 1) {


            $account_details = $login->fetch_assoc();


            $company_id = $account_details['company_id'];


            if (isset($_GET['get_tanks'])) {
                $responce = '';
                $sites_res = $db->exec_query('sites', ['*'], '', '', '', '', "company_id = $company_id");
                if ($sites_res->num_rows > 1) {

                    while ($site = $sites_res->fetch_assoc()) {
                        $site_name = $site['name'];
                        $responce = $responce . $site_name . "~";

                        $tanks_res = $db->exec_query('tanks', ['*'], '', '', '', '', "site_id = {$site['record_id']}");
                        while ($tank_info = $tanks_res->fetch_assoc()) {
                            $error_status = '';
                            $check_online_status = $db->exec_query('tank_level_log', ['*'], '', '', '', '', "tank_id = {$tank_info['record_id']} AND date_time_measured BETWEEN '$date_5min_ago' AND '$date_now'", " ORDER BY record_id ASC");
                            $distance = 0;
                            if ($check_online_status->num_rows > 0) {
                                $status = "ONLINE";
                                $row_measurements = $check_online_status->fetch_assoc();
                                $last_known_connection = $row_measurements['date_time_measured'];
                                $distance = $row_measurements['distance'];
                            } else {
                                $status = "OFFLINE";
                                $last_known_distance_res = $db->exec_query('tank_level_log', ['*'], '', '', '', '', "tank_id = {$tank_info['record_id']}", 'ORDER BY record_id DESC');
                                $info = $last_known_distance_res->fetch_assoc();
                                $last_known_connection = $info['date_time_measured'];
                                $distance = $info['distance'];
                            }


                            // eco 

                            // echo $tank_info['tank_type'];
                            if ($tank_info['tank_type'] == "H_C") {


                                $tank_volumes_ar =  calculate_horizontal_cylinder_volume($tank_info['radius_mm'], $distance, $tank_info['length_mm']);
                                if ($distance > ($tank_info['radius_mm'] * 2)) {
                                    $tank_volumes_ar['fluid_volume_liters'] = "0";
                                    $tank_volumes_ar['percentage_filled'] = "0";
                                    $error_status = "LEVEL SENSOR MALFUNCTION";
                                }
                            } else if ($tank_info['tank_type'] == "H_O") {
                                $tank_volumes_ar =  calculate_horizontal_oval_tank_volume($tank_info['semi_major_axis_mm'], $tank_info['semi_minor_axis_mm'], $distance, $tank_info['length_mm']);
                                if ($distance > ($tank_info['semi_minor_axis_mm'] * 2)) {
                                    $tank_volumes_ar['fluid_volume_liters'] = "0";
                                    $tank_volumes_ar['percentage_filled'] = "0";
                                    $error_status = "LEVEL SENSOR MALFUNCTION";
                                }
                            }
                            // var_dump($tank_volumes_ar);

                            $responce = $responce . $tank_info['name'] . "," . $status . ',' . $last_known_connection . "," . $tank_volumes_ar['fluid_volume_liters'] . "," . $tank_volumes_ar['total_volume_liters'] . "," . $tank_volumes_ar['percentage_filled'] . "," . $error_status . ',' . $tank_info['record_id'] . ',' . $tank_info['double_tanks']  . "//";
                        }
                        $responce = $responce . "||";
                    }
                } else {
                    echo "NO SITES REGITERED TO THIS COMPANY";
                }

                echo $responce;
            }

            if (isset($_GET['get_tank_log'])) {
                if (isset($_GET['tank_id'])) {
                    $tank_res = $db->exec_query('tanks', ['*'], '', '', '', '', "record_id = {$_GET['tank_id']}");
                    $tank_info = $tank_res->fetch_assoc();
                    $log_res = $db->exec_query('device_log', ['*'], '', '', '', '', "device_id = '{$tank_info['arduino_serial']}'", "ORDER BY record_id DESC LIMIT 40000");
                    $responce = "";
                    while ($log = $log_res->fetch_assoc()) {
                        $responce = $responce . $log["date_time"] . "," . $log['device_id'] . ',' . $log['text'] . '|';
                    }

                    echo $responce;
                } else {
                    echo "NO TANK ID PROVIDED";
                }
            }

            if (isset($_GET['get_sites'])) {
                $res = $db->exec_query('sites', ['*'], '', '', '', '', "company_id = $company_id");
                $responce = '';
                while ($data = $res->fetch_assoc()) {
                    $responce = $responce . $data['record_id'] . "," . $data['name'] . '|';
                }
                echo $responce;
            }

            if (isset($_GET['open_transaction'])) {
                if (isset($_GET['tank_qr'])) {
                    if (isset($_GET['asset_id'])) {
                        if (isset($_GET['user_id'])) {
                            if (isset($_GET['odo'])) {
                                if (strlen($_GET['tank_qr']) <= 1) {
                                    echo "NOT A VALID TANK ID";
                                } else {
                                    $date = date("Y-m-d H:i", strtotime("+ 2 hours"));
                                    $tank_id_res = $db->exec_query("tanks", ['*'], '', '', '', '', "arduino_serial = '{$_GET['tank_qr']}'");
                                    $tank_info = $tank_id_res->fetch_assoc();
                                    $insert = $db->insert("INSERT INTO fuel_movement (`tank_id`,`amount`,`status`,`date_time_opened`,`user_id`,`odo`,`asset_id`) VALUES ('{$tank_info['record_id']}','0','AUTHORISED','$date','{$_GET['user_id']}','{$_GET['odo']}','" . $company_id . "_{$_GET['asset_id']}')");
                                    echo $insert;
                                    // echo "INSERT INTO fuel_movement (`tank_id`,`amount`,`status`,`date_time_opened`,`user_id`,`odo`,`asset_id`) VALUES ('{$tank_info['record_id']}','0','AUTHORISED','$date','{$_GET['user_id']}','{$_GET['odo']}','" . $company_id . "_{$_GET['asset_id']}')";
                                }
                            } else {
                                echo "PLEASE PROVIDE A ODO";
                            }
                        } else {
                            echo "PLEASE PROVIDE USER ID";
                        }
                    } else {
                        echo "PEASE PROVIDE ASSET ID";
                    }
                } else {
                    echo "PLEASE PROVIDE THE TANK QR CODE";
                }
            }


            if (isset($_GET['get_transaction_details'])) {
                if (isset($_GET['tran_id'])) {
                    $res = $db->exec_query('fuel_movement', ['*'], '', '', '', '', "record_id = {$_GET['tran_id']}");

                    $row = $res->fetch_assoc();

                    echo $row['status'] . "|" . $row['amount'] . "|" . $row['flow_rate'];
                } else {
                    echo "NO TRASNACTION DETAILS PROVIDED";
                }
            }

            if (isset($_GET['transactions_report'])) {
                $where = " 1 ";
                // echo $_GET['from_date'];
                // echo $_GET['asset_id'];
                if (strlen($_GET['from_date']) > 1) {

                    $where = $where . " AND date_time_opened BETWEEN '{$_GET['from_date']} 00:00' AND '{$_GET['to_date']} 23:59'";
                }

                if ($_GET['asset_id'] != 'ALL') {
                    $where = $where . " AND asset_id = '" . $company_id . "_" . $_GET['asset_id'] . "'";
                }

                $site_id_res = $db->exec_query('sites', ['*'], '', '', '', '', "company_id = $company_id");
                $responce = "";

                while ($site = $site_id_res->fetch_assoc()) {
                    $responce = $responce . $site['name'] . "~";


                    $get_tanks_res = $db->exec_query('tanks', ['*'], '', '', '', '', "site_id = {$site['record_id']}");
                    while ($tank_id = $get_tanks_res->fetch_assoc()) {
                        $responce = $responce . $tank_id['name'] . "$";

                        $res = $db->exec_query('fuel_movement', ['*'], '', '', '', '', $where . " AND tank_id = {$tank_id['record_id']}", "ORDER BY record_id DESC");
                        // echo $where;
                        while ($row = $res->fetch_assoc()) {
                            $tank_res = $db->exec_query('tanks', ['*'], '', '', '', '', "record_id = {$row['tank_id']}");
                            $tank_info = $tank_res->fetch_assoc();
                            $responce = $responce . $row['amount'] . ',' . $row['status'] . ',' . $row['date_time_opened'] . ',' . $row['date_time_closed'] . ',' . $row['user_id'] . ',' . $row['asset_id'] . ',' . $row['odo'] . ',' . $row['flow'] . '|';
                        }
                        $responce = $responce . "//";
                    }
                    $responce = $responce . "[]";
                }

                echo $responce;
            }

            if (isset($_GET['get_site_tanks'])) {
                if (isset($_GET['site_id'])) {
                    $res = $db->exec_query('tanks', ['*'], '', '', '', '', "site_id = {$_GET['site_id']}");
                    $responce = "";
                    while ($row = $res->fetch_assoc()) {
                        // var_dump($row);
                        // echo $row['record_id'];
                        $responce = $responce . $row['record_id'] . ',' . $row['name'] .  '|';
                    }
                    echo $responce;
                } else {
                    echo "NO SITE ID PROVIDED";
                }
            }
        } else {
            echo "CREDINTIALS INCORRECT OR MORE THAN ONE USER OR INACTIVE";
        }
    } else {
        echo "NO PASSWORD";
    }
} else {
    echo "NO USERNAME";
}
