<?php
class functions
{
    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_vertical_cylinder_volume($radius_m, $liquid_level_from_top_m, $height_m)
    {
        // Calculate liquid height
        $liquid_height_m = $height_m - $liquid_level_from_top_m;
        if ($liquid_height_m < 0)
            $liquid_height_m = 0; // prevent negative

        // Volumes in cubic meters
        $liquid_volume_m3 = pi() * pow($radius_m, 2) * $liquid_height_m;
        $total_volume_m3 = pi() * pow($radius_m, 2) * $height_m;

        // Convert cubic meters → liters
        $liquid_volume_liters = $liquid_volume_m3 * 1000;
        $total_volume_liters = $total_volume_m3 * 1000;

        // Percentage filled
        $percentage_filled = ($total_volume_liters > 0)
            ? ($liquid_volume_liters / $total_volume_liters) * 100
            : 0;

        return array(
            'fluid_volume_liters' => round($liquid_volume_liters, 2),
            'total_volume_liters' => round($total_volume_liters, 2),
            'percentage_filled' => round($percentage_filled, 2)
        );
    }


    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)
        );
    }

    function total_liters_for_tank($tank_id)
    {
        $db = new db();
        $date = date("Y-m-d");
        $tank_res = $db->query("tanks", "SELECT SUM(amount) as total FROM fuel_movement as fm LEFT JOIN clients as c ON fm.client_id = c.record_id WHERE (fm.date_time_closed BETWEEN '$date 00:00' AND '$date 23:59' AND fm.tank_id = $tank_id AND fm.company_id = {$_SESSION['company_id']} AND c.company_id = {$_SESSION['company_id']} AND c.exclude_from_reports != 1) OR (fm.date_time_closed BETWEEN '$date 00:00' AND '$date 23:59' AND fm.tank_id = $tank_id AND fm.company_id = {$_SESSION['company_id']} AND fm.status = 'MANUAL OVERRIDE' AND fm.client_id = 0)");
        return $tank_res->fetch_assoc()['total'] / 1000;
    }


    function total_liters_for_today()
    {
        $db = new db();
        $date = date("Y-m-d");
        $tank_res = $db->query("tanks", "SELECT SUM(amount) as total FROM fuel_movement as fm LEFT JOIN clients as c ON fm.client_id = c.record_id WHERE (fm.tank_id IN ({$_SESSION['tanks']}) AND fm.date_time_closed BETWEEN '$date 00:00' AND '$date 23:59' AND fm.company_id = {$_SESSION['company_id']} AND c.company_id = {$_SESSION['company_id']} AND fm.status = 'RFID' AND c.exclude_from_reports != 1)OR( fm.tank_id IN ({$_SESSION['tanks']}) AND fm.date_time_closed BETWEEN '$date 00:00' AND '$date 23:59' AND fm.company_id = {$_SESSION['company_id']} AND  fm.status = 'MANUAL OVERRIDE' AND fm.client_id = 0)");
        // echo "SELECT SUM(amount) as total FROM fuel_movement WHERE date_time_closed BETWEEN '$date 00:00' AND '$date 23:59' AND company_id = {$_SESSION['company_id']}";
        return $tank_res->fetch_assoc()['total'] / 1000;
    }


    function total_liters_for_today_excluded_tags()
    {
        $db = new db();
        $date = date("Y-m-d");
        $tank_res = $db->query("tanks", "SELECT SUM(amount) as total FROM fuel_movement as fm LEFT JOIN clients as c ON fm.client_id = c.record_id WHERE fm.tank_id IN ({$_SESSION['tanks']}) AND fm.date_time_closed BETWEEN '$date 00:00' AND '$date 23:59' AND fm.company_id = {$_SESSION['company_id']} AND c.company_id = {$_SESSION['company_id']} AND c.exclude_from_reports = 1");
        // echo "SELECT SUM(amount) as total FROM fuel_movement WHERE date_time_closed BETWEEN '$date 00:00' AND '$date 23:59' AND company_id = {$_SESSION['company_id']}";
        return $tank_res->fetch_assoc()['total'] / 1000;
    }

    function get_total_tanks_for_client($client_id)
    {
        $db = new db();
        $tank_res = $db->query("tanks", "SELECT * FROM tanks WHERE client_id = $client_id");
        return $tank_res->num_rows;
    }

    function get_total_max_capacity_for_client($client_id)
    {
        $db = new db();
        $total = 0;
        $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE client_id = $client_id");
        // get tank level log
        while ($tank = $tanks_res->fetch_assoc()) {

            if ($tank['tank_type'] == "H_C") {
                $data = $this->calculate_horizontal_cylinder_volume($tank['radius_mm'], 0, $tank['length_mm']);
            } else {
                $data = $this->calculate_vertical_cylinder_volume($tank['radius_mm'], 0, $tank['length_mm']);
            }
            $total += $data['total_volume_liters'];
        }
        return $total;
    }

    function get_capacity_for_client($client_id)
    {
        $db = new db();
        $total = 0;
        $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE client_id = $client_id");
        while ($tank = $tanks_res->fetch_assoc()) {
            $log_res = $db->query("tank_level_log", "SELECT * FROM tank_level_log WHERE tank_id = {$tank['record_id']} ORDER BY record_id DESC LIMIT 1");
            $log = $log_res->fetch_assoc();
            if ($tank['tank_type'] == "H_C") {
                $data = $this->calculate_horizontal_cylinder_volume($tank['radius_mm'], ($tank['radius_mm'] * 2) - ($log['distance'] + $tank['add_to_distance']), $tank['length_mm']);
            } else {
                $data = $this->calculate_vertical_cylinder_volume($tank['radius_mm'], ($tank['radius_mm'] * 2) - ($log['distance'] + $tank['add_to_distance']), $tank['length_mm']);
            }
            $total += $data['fluid_volume_liters'];
        }
        return $total;
    }

    function get_total_tanks()
    {
        $db = new db();
        $tank_res = $db->query("tanks", "SELECT * FROM tanks");
        return $tank_res->num_rows;
    }

    function get_total_clients(){
        $db = new db();
        $tank_res = $db->query("clients", "SELECT * FROM clients");
        return $tank_res->num_rows;
    }
    function get_total_tanks_for_sites($site_id)
    {
        $db = new db();
        $tank_res = $db->query("tanks", "SELECT * FROM tanks WHERE site_id = $site_id");
        return $tank_res->num_rows;
    }
    function get_total_max_capacity_for_sites($site_id)
    {
        $db = new db();
        $total = 0;
        $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE site_id = $site_id");
        while ($tank = $tanks_res->fetch_assoc()) {
            if ($tank['tank_type'] == "H_C") {
                $data = $this->calculate_horizontal_cylinder_volume($tank['radius_mm'], 0, $tank['length_mm']);
            } else {
                $data = $this->calculate_vertical_cylinder_volume($tank['radius_mm'], 0, $tank['length_mm']);
            }
            $total += $data['total_volume_liters'];
        }
        return $total;
    }


    function get_capacity_for_sites($site_id)
    {
        $db = new db();
        $total = 0;
        $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE site_id = $site_id");
        // get tank level log
        while ($tank = $tanks_res->fetch_assoc()) {
            $log_res = $db->query("tank_level_log", "SELECT * FROM tank_level_log WHERE tank_id = {$tank['record_id']} ORDER BY record_id DESC LIMIT 1");
            if ($log_res->num_rows == 0) {
                $log['distance'] = 0;
            }
            $log = $log_res->fetch_assoc();
            if ($tank['tank_type'] == "H_C") {
                $data = $this->calculate_horizontal_cylinder_volume($tank['radius_mm'], ($tank['radius_mm'] * 2) - ($log['distance'] + $tank['add_to_distance']), $tank['length_mm']);
            } else {
                $data = $this->calculate_vertical_cylinder_volume($tank['radius_mm'], ($tank['radius_mm'] * 2) - ($log['distance'] + $tank['add_to_distance']), $tank['length_mm']);
            }
            $total += $data['fluid_volume_liters'];
        }
        return $total;
    }

    function get_progress_bar($current, $max)
    {
        // 1. Convert to floats and handle division by zero
        $current = (float) $current;
        $max = (float) $max;
        $percent = ($max > 0) ? ($current / $max) * 100 : 0;

        // 2. Clamp percentage between 0 and 100
        $percent = max(0, min(100, $percent));

        // 3. Determine Color (Apple System Colors)
        $color = '#34C759'; // Green (Standard)
        if ($percent <= 20) {
            $color = '#FF3B30'; // Red (Critical)
        } elseif ($percent <= 50) {
            $color = '#FF9500'; // Orange (Low)
        }

        // 4. Return the HTML string
        $html = '
    <div class="progress-container" style="height: 18px; width: 100%; background-color: #E5E5EA; border-radius: 10px; overflow: hidden; position: relative; border: 1px solid rgba(0,0,0,0.03);">
        <div class="progress-bar" style="width: ' . $percent . '%; background-color: ' . $color . '; height: 100%; border-radius: 10px; transition: width 0.8s ease-in-out; display: flex; align-items: center; justify-content: center;">
            <span style="color: white; font-size: 10px; font-weight: bold; text-shadow: 0 1px 2px rgba(0,0,0,0.2);">' . round($percent) . '%</span>
        </div>
    </div>';

        return $html;
    }

    function getNamesFromIds($table, $ids)
    {
        $db = new db();
        if (empty($ids)) {
            return '<span class="label-none">None</span>';
        }

        // 1. Prepare and clean the IDs
        $idArray = explode(',', $ids);

        $idString = implode(',', $idArray);

        // 2. Determine column name (users table uses 'username')
        $nameCol = ($table === 'users') ? 'username' : 'name';

        // 3. Execute query using your specific syntax
        $sql = "SELECT $nameCol FROM $table WHERE record_id IN ($idString) ORDER BY $nameCol ASC";
        $res = $db->query($table, $sql);

        $badges = [];

        // 4. Fetch data using your specific syntax
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $name = htmlspecialchars($row[$nameCol]);
                $badges[] = "<span class='badge-item' style='font-size:10px; background:#b2deff; color:#000000; padding:2px 6px; border-radius:4px; margin-left:5px;'>$name</span>";
            }
        }

        return !empty($badges) ? implode(' ', $badges) : '<span class="label-none">None</span>';
    }


    function add_to_handler($type, $tank_ids, $user_ids,$subject,$html_body)
    {
        $db = new db();
        $sql = "INSERT INTO event_handler (type_of_notification, tank_ids, user_ids,`subject`,body) VALUES ('$type', '$tank_ids', '$user_ids','$subject','$html_body')";
        $db->query("event_handler", $sql);
    }

    function ready_to_save($var){
        $var = str_replace("'", "\'", $var);
        $var = str_replace('"', '\"', $var);
        return $var;
    }
    
}

function renderTankBlock($tank_id, $includeWrapper = true, $first_time_load = false)
{
    $db = new db();

    // ... [Existing DB Fetching Logic] ...
    $tank = $db->query("tanks", "SELECT * FROM tanks WHERE record_id = $tank_id");
    $tank = $tank->fetch_assoc();
    $name = $tank['name'];
    $radius = $tank['radius_mm'];
    $length = $tank['length_mm'];
    $tank_type = $tank['tank_type'];
    $add_to_distance = $tank['add_to_distance'];

    if (!$first_time_load) {

        $latest_log_res = $db->query("tank_level_log", "SELECT * FROM tank_level_log WHERE tank_id = $tank_id ORDER BY record_id DESC LIMIT 1");
        $latest_log = $latest_log_res->fetch_assoc();
        $distance = $latest_log['distance'] ?? 0;
        $wifi_signal = $latest_log['wifi_signal'] ?? 0;
        $wifi_name = $latest_log['wifi_name'] ?? 'N/A';
        $date_time = $latest_log['date_time_measured'] ?? date('Y-m-d H:i:s');

        $func = new functions();
        $data = $func->calculate_horizontal_cylinder_volume($radius, ($radius * 2) - ($distance + $add_to_distance), $length);

        $full = $data['total_volume_liters'];
        $current = $data['fluid_volume_liters'];
        $percentage = ($full > 0) ? min(100, max(0, ($current / $full) * 100)) : 0;
    } else {
        $percentage = 0;
        $full = 0;
        $current = 0;
        $date_time = "N/A";
        $wifi_signal = 0;
        $wifi_name = 'N/A';
    }

    // Color Logic
    if ($percentage < 10) {
        $barColor = '#FF3B30';
    } elseif ($percentage < 25) {
        $barColor = '#FF9500';
    } elseif ($percentage < 50) {
        $barColor = '#0071E3';
    } elseif ($percentage < 75) {
        $barColor = '#34C7C4';
    } else {
        $barColor = '#28CD41';
    }

    // Signal Logic (Standard dBm ranges)
    $bars = 0;
    if ($wifi_signal > -55)
        $bars = 4;
    elseif ($wifi_signal > -70)
        $bars = 3;
    elseif ($wifi_signal > -85)
        $bars = 2;
    elseif ($wifi_signal > -95)
        $bars = 1;

    $output = '';

    // Only echo the wrapper if specifically asked (first load)
    if ($includeWrapper) {
        $output .= '<div id="tank-wrapper-' . $tank_id . '" class="tank-wrapper" data-id="' . $tank_id . '">';
    }

    $output .= '
    <div class="tank-card compact">
        <div class="tank-local-loader"><div class="apple-spinner-small"></div></div>
        <div class="tank-header">
            <div class="tank-info">
                <span class="tank-name">' . htmlspecialchars($name) . '</span>
                <span class="tank-status">' . date("d M Y • H:i:s", strtotime($date_time)) . '</span>
            </div>
  
        </div>
        <div class="tank-stats">
            <span class="current-liters">' . number_format($current, 0) . ' <small>L</small></span>
            <span class="full-liters">/ ' . number_format($full, 0) . ' L</span>
        </div>
        <div class="progress-container">
            <div class="progress-bar-bg">
                <div class="progress-bar-fill" style="width: ' . $percentage . '%; background-color: ' . $barColor . ';"></div>
            </div>
            <span class="percentage-label">' . round($percentage) . '%</span>
        </div>
        <div class="tank-footer">
            <div class="wifi-info" style="display: flex; align-items: center; gap: 8px;">
                <div class="signal-bars-wrapper" title="' . $wifi_signal . ' dBm" style="display: flex; align-items: flex-end; gap: 2px; height: 12px;">
                    <div class="bar ' . ($bars >= 1 ? 'active' : '') . '" style="width: 3px; height: 4px; border-radius: 1px; background-color: ' . ($bars >= 1 ? '#34C759' : '#D2D2D7') . ';"></div>
                    <div class="bar ' . ($bars >= 2 ? 'active' : '') . '" style="width: 3px; height: 6px; border-radius: 1px; background-color: ' . ($bars >= 2 ? '#34C759' : '#D2D2D7') . ';"></div>
                    <div class="bar ' . ($bars >= 3 ? 'active' : '') . '" style="width: 3px; height: 8px; border-radius: 1px; background-color: ' . ($bars >= 3 ? '#34C759' : '#D2D2D7') . ';"></div>
                    <div class="bar ' . ($bars >= 4 ? 'active' : '') . '" style="width: 3px; height: 10px; border-radius: 1px; background-color: ' . ($bars >= 4 ? '#34C759' : '#D2D2D7') . ';"></div>
                </div>
                <span style="font-size: 10px; font-weight: 500; color: #86868B;">' . htmlspecialchars($wifi_name) . '</span>
            </div>
        </div>
    </div>';

    if ($includeWrapper) {
        $output .= '</div>';
    }

    echo $output;
}