<?php

require_once './config/database.php';

$query = '
            SELECT
                CASE WHEN `time` + 10 < CAST(DATE_FORMAT(CURRENT_TIMESTAMP, \'%H%i%s\') AS SIGNED) AND `date` = CAST(DATE_FORMAT(CURRENT_TIMESTAMP, \'%y%m%d\') AS SIGNED) THEN 0
                     ELSE `U`
                END AS `U`, 
                CASE WHEN `time` + 10 < CAST(DATE_FORMAT(CURRENT_TIMESTAMP, \'%H%i%s\') AS SIGNED) AND `date` = CAST(DATE_FORMAT(CURRENT_TIMESTAMP, \'%y%m%d\') AS SIGNED) THEN 0
                     ELSE `I`
                END AS `I`, 
                CASE WHEN `time` + 10 < CAST(DATE_FORMAT(CURRENT_TIMESTAMP, \'%H%i%s\') AS SIGNED) AND `date` = CAST(DATE_FORMAT(CURRENT_TIMESTAMP, \'%y%m%d\') AS SIGNED) THEN 0
                     ELSE `p`
                END AS `P`,
                CASE WHEN `time` + 10 < CAST(DATE_FORMAT(CURRENT_TIMESTAMP, \'%H%i%s\') AS SIGNED) AND `date` = CAST(DATE_FORMAT(CURRENT_TIMESTAMP, \'%y%m%d\') AS SIGNED) THEN 2
                     ELSE `R`
                END AS `R`
            FROM 
                `power` 
            ORDER BY 
                `date` DESC, 
                `time` DESC 
            LIMIT 1
        ';

$result = mysql_query($query);

if (mysql_num_rows($result))
{
    echo json_encode(mysql_fetch_assoc($result));
}
else
{
    // nenačtena data z DB
    $array = array(
        'U' => 0,
        'I' => 0,
        'p' => 0,
        'R' => 2
    );
    
    echo json_encode($array);
}

/*$rows = array();
    //flag is not needed
    $flag = true;
    $table = array();
    $table['cols'] = array(

        // Labels for your chart, these represent the column titles
        // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
        array('label' => 'U', 'type' => 'number'),
        array('label' => 'I', 'type' => 'number'),
        array('label' => 'P', 'type' => 'number')

    );

    $rows = array();
    while($r = mysql_fetch_assoc($power_db)) {
        $temp = array();
        // the following line will be used to slice the Pie chart
        // Values of each slice
        $temp[] = array('v' => (int) $r['U']); 
        $temp[] = array('v' => (int) $r['I']); 
        $temp[] = array('v' => (int) $r['P']); 
        
        $rows[] = array('c' => $temp);
    }

    $table['rows'] = $rows;
    echo json_encode($table);

*/