<?php
$mysqli = new mysqli("localhost", "root", "", "ugo");
$mysqli->set_charset("utf8");

if ($mysqli->connect_error) {
    die("Povezivanje na bazu nije uspjelo: " . $mysqli->connect_error);
}

function getBaseUrl($mysqli) {
    $query = "SELECT value FROM settings WHERE name = 'putanja.http' LIMIT 1";
    $result = $mysqli->query($query);
    if ($result->num_rows > 0) {
        return $result->fetch_assoc()['value'];
    } else {
        die("Nema URL-a sa imenom 'putanja.http' u bazi.");
    }
}

$baseUrl = getBaseUrl($mysqli);
$loginUrl = "$baseUrl/users/login";
$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];

$postData = [
    'data[User][username]' => 'Kasapro',
    'data[User][password]' => '6664999'
];
$ch = curl_init($loginUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$response = curl_exec($ch);
curl_close($ch);

if (strpos($response, 'POČETNA') === false) {
    die("Prijava nije uspjela");
}

$reportUrl = "$baseUrl/reports/pregled_prodaje_po_normativu";
$reportData = [
    'data[Filter][date_start]' => $startDate,
    'data[Filter][date_end]' => $endDate,
    'submit_report' => 2
];

$ch = curl_init($reportUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($reportData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$response = curl_exec($ch);
curl_close($ch);

if (strpos($response, 'Izvještaj je kreiran') === false) {
    die("Greška prilikom generiranja izvještaja");
}

echo "Izvještaj je kreiran.";
?>
