<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    if (isset($_POST['key'])&&($_POST['key'] === 'pricepassword')&&isset($_POST['startDate'])&&$_POST['startDate']!=""&&isset($_POST['endDate'])&&$_POST['endDate']!=""&&isset($_POST['price'])&&$_POST['price']!=""&&isset($_POST['id'])&&$_POST['id']!="") {
        if($_POST['startDate']<=$_POST['endDate']){
            require('../connect.php');
    
            $conn = new mysqli($host, $user, $pass, $database);

            $checkBillingSql = "SELECT * FROM `billings` WHERE (`id` NOT IN ('{$_POST['id']}')) AND ((`start_date` >= '{$_POST['startDate']}' AND `end_date` <= '{$_POST['endDate']}') OR (`end_date` >= '{$_POST['startDate']}' AND `start_date` <= '{$_POST['endDate']}'))";
    
            $checkBilling = mysqli_query($conn, $checkBillingSql);

            // echo $checkBillingSql;
            
            if(mysqli_num_rows($checkBilling)==0){
                $price = str_replace(",",".",$_POST['price']);
                // $sql = "UPDATE `energy` SET `kWh_price`='{$_POST['price']}' WHERE `date` >= '{$_POST['startDate']}' AND `date` <= '{$_POST['endDate']}'";
                $sql = "UPDATE `billings` SET `start_date`='{$_POST['startDate']}',`end_date`='{$_POST['endDate']}',`price`='{$price}' WHERE `id` = '{$_POST['id']}'";
                mysqli_query($conn, $sql);
                $response = array("success"=>"yes");
            }else{
                $response = array('success' => 'no',
                        'message' => 'Dane nakładają się');
            }
    
    
            // foreach ($checkBilling as $billing) {
            //     print_r($billing);
            //     echo "<br>";
            // }
    
            mysqli_close($conn);
        }else{
            $response = array('success' => 'no',
                        'message' => 'Błąd daty');
        }
    }else{
        $response = array('success' => 'no',
                        'message' => 'Błąd autoryzacji i/lub błędne dane');
    }
    header('Content-Type: application/json');
    echo json_encode($response);
?>