<?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'] != "") {
        if ($_POST['startDate'] <= $_POST['endDate']) {
            require('../connect.php');

            $conn = new mysqli($host, $user, $pass, $database);

            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }

            $startDate = $conn->real_escape_string($_POST['startDate']);
            $endDate = $conn->real_escape_string($_POST['endDate']);
            $price = str_replace(",", ".", $conn->real_escape_string($_POST['price']));

            $checkBilling = mysqli_query($conn, "SELECT * FROM `billings` WHERE (`start_date` >= '$startDate' AND `end_date` <= '$endDate') OR (`end_date` >= '$startDate' AND `start_date` <= '$endDate')");

            if (mysqli_num_rows($checkBilling) == 0) {
                $sql = "INSERT INTO `billings` VALUES (NULL, '$startDate', '$endDate', '$price')";
                if ($conn->query($sql) === TRUE) {
                    $last_id = $conn->insert_id;
                    $last_data = array('id' => $last_id,
                                        'startDate' => $startDate,
                                        'endDate' => $endDate,
                                        'price' => $price);
                    $response = array('success' => 'yes', 'message' => $last_data);
                } else {
                    $response = array('success' => 'no', 'message' => 'Błąd przy dodawaniu danych: ' . $conn->error);
                }
            } else {
                $response = array('success' => 'no', 'message' => 'Dane nakładają się');
            }

            $conn->close();
        } 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);
?>
