<?php


class html
{

    function generateCircularProgressBar($min, $max, $current, $symbol = '', $round = 0)
    {
        // Ensure the current value is within bounds
        $actual_current = $current;
        $current = max($min, min($current, $max));

        // Calculate percentage of completion
        $percentage = (($current - $min) / ($max - $min)) * 100;

        // Calculate circle properties
        $radius = 50;
        $circumference = 2 * pi() * $radius;
        $offset = $circumference - ($percentage / 100) * $circumference;

        // Determine the color based on percentage
        if ($percentage <= 25) {
            $color = "#2ecc71"; // Green
        } elseif ($percentage <= 50) {
            $color = "#3498db"; // Blue
        } elseif ($percentage <= 75) {
            $color = "#e67e22"; // Orange
        } else {
            $color = "#e74c3c"; // Red
        }

        // Generate the SVG with CSS animation
        return '
    <style>
        .progress-circle {
            transition: stroke-dashoffset 1s ease-in-out, stroke 1s ease-in-out;
        }
    </style>
    <svg width="40%" height="80%" viewBox="0 0 120 120">
        <circle cx="60" cy="60" r="' . $radius . '" stroke="#d3d3d3" stroke-width="10" fill="none"/>
        <circle class="progress-circle" cx="60" cy="60" r="' . $radius . '" stroke="' . $color . '" stroke-width="10" fill="none" 
                stroke-dasharray="' . $circumference . '" 
                stroke-dashoffset="' . $offset . '" 
                transform="rotate(-90 60 60)"/>
        
        <!-- Current value and symbol in the center -->
        <text x="50%" y="50%" text-anchor="middle" dy=".3em" font-size="20" font-family="Arial" fill="#000">
            ' . number_format($actual_current, $round, '.', ',') . $symbol . '
        </text>
        
        <!-- Min value at the top -->
        <text x="50%" y="30%" text-anchor="middle" font-size="12" font-family="Arial" fill="#000">
            ' . number_format($min, $round, '.', ',') . $symbol . '
        </text>
        
        <!-- Max value at the bottom -->
        <text x="50%" y="75%" text-anchor="middle" font-size="12" font-family="Arial" fill="#000">
            ' . number_format($max, $round, '.', ',')  . $symbol . '
        </text>
    </svg>';
    }

    function generateLineGraph($dataPoints1, $dataPoints2, $height = 300, $xLabel = 'X Axis', $yLabel = 'Y Axis', $leftPadding = 80, $minYCustom = null, $maxYCustom = null)
    {
        // Ensure both datasets are not empty
        if (empty($dataPoints1) || empty($dataPoints2)) {
            return '<p>No data available for the graph.</p>';
        }
    
        // Combine both datasets to find the global min and max Y values for scaling
        $yValues1 = array_column($dataPoints1, 1);
        $yValues2 = array_column($dataPoints2, 1);
        $yValues = array_merge($yValues1, $yValues2);
    
        // Ensure y-values are numeric
        foreach ($yValues as $value) {
            if (!is_numeric($value)) {
                return '<p>Error: Y values must be numeric.</p>';
            }
        }
    
        // Automatically calculate min and max Y values if not provided
        $minY = $minYCustom !== null ? $minYCustom : min($yValues);
        $maxY = $maxYCustom !== null ? $maxYCustom : max($yValues);
    
        // Avoid division by zero for scaling
        if ($maxY === $minY) {
            $minY = $minY - 1;
            $maxY = $maxY + 1;
        }
    
        // Padding for the graph (dynamic based on the $leftPadding parameter)
        $padding = 40; // Top and bottom padding
        $rightPadding = 40; // Right padding
        $width = 2000; // Default width for calculations
    
        // Scaling factor for the y-axis to fit the graph within the height
        $yScale = ($height - 2 * $padding) / ($maxY - $minY);
    
        // Generate the path data for the first dataset
        $pathData1 = '';
        foreach ($dataPoints1 as $index => $point) {
            // Convert x value (timestamp) to a numeric index for plotting
            $x = $leftPadding + ($index / (count($dataPoints1) - 1)) * ($width - $leftPadding - $rightPadding);
            // Ensure y is numeric and scaled properly
            $y = $height - $padding - ((float)$point[1] - $minY) * $yScale;
    
            $pathData1 .= ($index === 0) ? "M$x,$y" : " L$x,$y";
        }
    
        // Generate the path data for the second dataset
        $pathData2 = '';
        foreach ($dataPoints2 as $index => $point) {
            $x = $leftPadding + ($index / (count($dataPoints2) - 1)) * ($width - $leftPadding - $rightPadding);
            $y = $height - $padding - ((float)$point[1] - $minY) * $yScale;
    
            $pathData2 .= ($index === 0) ? "M$x,$y" : " L$x,$y";
        }
    
        // Generate grid lines
        $gridLines = '';
        $numYGridLines = 3;
    
        // X-axis grid lines and labels
        $numXGridLines = min(4, count($dataPoints1) - 1);
    
        // Y-axis grid lines
        for ($i = 0; $i <= $numYGridLines; $i++) {
            $y = $height - $padding - ($i / $numYGridLines) * ($height - 2 * $padding);
            $gridLines .= '<line x1="' . $leftPadding . '" y1="' . $y . '" x2="' . ($width - $rightPadding) . '" y2="' . $y . '" stroke="#d3d3d3" stroke-dasharray="4" />';
        }
    
        // X-axis grid lines and labels
        $xLabelsOutput = '';
        for ($i = 0; $i <= $numXGridLines; $i++) {
            $x = $leftPadding + ($i / $numXGridLines) * ($width - $leftPadding - $rightPadding);
            $gridLines .= '<line x1="' . $x . '" y1="' . $padding . '" x2="' . $x . '" y2="' . ($height - $padding) . '" stroke="#d3d3d3" stroke-dasharray="4" />';
            $xLabelsOutput .= '<text x="' . $x . '" y="' . ($height - $padding + 15) . '" text-anchor="middle" font-size="10" font-family="Arial">' . htmlspecialchars((string)$dataPoints1[$i * (count($dataPoints1) - 1) / $numXGridLines][0]) . '</text>';
        }
    
        // Y-axis labels
        $yLabelsOutput = '';
        foreach (range(0, $numYGridLines) as $i) {
            $yValue = $minY + ($i / $numYGridLines) * ($maxY - $minY);
            $yPos = $height - $padding - (($yValue - $minY) * $yScale);
            $yLabelsOutput .= '<text x="' . ($leftPadding - 10) . '" y="' . $yPos . '" text-anchor="end" font-size="10" font-family="Arial">' . htmlspecialchars(round($yValue, 2)) . '</text>';
        }
    
        // Generate the SVG code
        return '
        <svg width="100%" height="' . $height . '" viewBox="0 0 ' . $width . ' ' . $height . '" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet">
            <!-- X and Y axis lines -->
            <line x1="' . $leftPadding . '" y1="' . ($height - $padding) . '" x2="' . ($width - $rightPadding) . '" y2="' . ($height - $padding) . '" stroke="black" />
            <line x1="' . $leftPadding . '" y1="' . $padding . '" x2="' . $leftPadding . '" y2="' . ($height - $padding) . '" stroke="black" />
            
            <!-- Grid lines -->
            ' . $gridLines . '
    
            <!-- Line graph path for the first dataset -->
            <path d="' . $pathData1 . '" fill="none" stroke="blue" stroke-width="2" />
    
            <!-- Line graph path for the second dataset -->
            <path d="' . $pathData2 . '" fill="none" stroke="red" stroke-width="2" />
    
            <!-- X-axis labels -->
            ' . $xLabelsOutput . '
    
            <!-- Y-axis labels -->
            ' . $yLabelsOutput . '
    
            <!-- X-axis label -->
            <text x="' . ($width / 2) . '" y="' . ($height - 5) . '" text-anchor="middle" font-size="14" font-family="Arial">' . htmlspecialchars($xLabel) . '</text>
    
            <!-- Y-axis label (rotated for vertical display) -->
            <text x="15" y="' . ($height / 2) . '" text-anchor="middle" font-size="14" font-family="Arial" transform="rotate(-90 15,' . ($height / 2) . ')">' . htmlspecialchars($yLabel) . '</text>
        </svg>';
    }
    



    function getCurrentWeather($apiKey, $city = 'Mbombela', $countryCode = 'ZA')
    {
        // Build the API URL
        $url = "https://api.openweathermap.org/data/2.5/weather?q={$city},{$countryCode}&appid={$apiKey}&units=metric";

        // Initialize cURL session
        $curl = curl_init();

        // Set cURL options
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);

        // Execute cURL request and fetch the response
        $response = curl_exec($curl);

        // Close the cURL session
        curl_close($curl);

        // Check if the response is valid JSON
        if ($response === false) {
            return "Error fetching weather data.";
        }

        $weatherData = json_decode($response, true);

        // Check if the API call was successful
        if (isset($weatherData['cod']) && $weatherData['cod'] == 200) {
            // Extract required data
            $temperature = $weatherData['main']['temp'];
            $humidity = $weatherData['main']['humidity'];
            $weatherCondition = $weatherData['weather'][0]['description'];
            $uvIndex = self::getUVIndex($weatherData['coord']['lat'], $weatherData['coord']['lon'], $apiKey);

            // Check for rain data (in mm)
            $rainAmount = isset($weatherData['rain']['1h']) ? $weatherData['rain']['1h'] : 0;
            $chanceOfRain = $rainAmount > 0 ? 'Yes' : 'No';

            return [
                'temperature' => $temperature,
                'feels_like' => $weatherData['main']['feels_like'],
                'pressure' => $weatherData['main']['pressure'],
                'humidity' => $humidity,
                'uvIndex' => $uvIndex,
                'weatherCondition' => $weatherCondition,
                'chanceOfRain' => $chanceOfRain,
                'rainAmount' => $rainAmount . ' mm'  // Rainfall in mm
            ];
        } else {
            return "Error: " . $weatherData['message'];
        }
    }

    function getUVIndex($lat, $lon, $apiKey)
    {
        // Build the API URL for UV index
        $url = "https://api.openweathermap.org/data/2.5/uvi?lat={$lat}&lon={$lon}&appid={$apiKey}";

        // Initialize cURL session
        $curl = curl_init();

        // Set cURL options
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);

        // Execute cURL request and fetch the response
        $response = curl_exec($curl);

        // Close the cURL session
        curl_close($curl);

        // Check if the response is valid JSON
        if ($response === false) {
            return "Error fetching UV index.";
        }

        $uvData = json_decode($response, true);

        // Check if the API call was successful
        if (isset($uvData['value'])) {
            return $uvData['value'];
        } else {
            return "Error fetching UV index.";
        }
    }
}
