<?php
require_once "config.php";
require_once "auth.php";
require_once "vehicle_options.php";
require_once "email_helper.php";
require_once "settings_helper.php";
requireLogin();

$success = false;
$error = null;
$voznja = null;

if (!isset($_GET['id'])) {
    header("Location: index.php");
    exit();
}

$id = (int)$_GET['id'];

$stmt = $conn->prepare("SELECT * FROM voznje WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$voznja = $result->fetch_assoc();

if (!$voznja) {
    header("Location: index.php");
    exit();
}

if (!isAdmin() && $voznja['komitent_id'] != $_SESSION['user']['komitent_id']) {
    header("Location: index.php");
    exit();
}

if (!isAdmin() && $voznja['status'] === 'Obrisano') {
    header("Location: index.php?error=Ne možete menjati obrisanu vožnju");
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $datum = $_POST["datum"];
    $vreme = $_POST["vreme"];
    $broj_leta = trim($_POST["broj_leta"]);
    $polazna_adresa = trim($_POST["polazna_adresa"]);
    $dolazna_adresa = trim($_POST["dolazna_adresa"]);
    $polazna_place_id = $_POST['polazna_place_id'] ?? null;
    $dolazna_place_id = $_POST['dolazna_place_id'] ?? null;
    $polazna_lat = ($_POST['polazna_lat'] ?? '') !== '' ? floatval($_POST['polazna_lat']) : null;
    $polazna_lng = ($_POST['polazna_lng'] ?? '') !== '' ? floatval($_POST['polazna_lng']) : null;
    $dolazna_lat = ($_POST['dolazna_lat'] ?? '') !== '' ? floatval($_POST['dolazna_lat']) : null;
    $dolazna_lng = ($_POST['dolazna_lng'] ?? '') !== '' ? floatval($_POST['dolazna_lng']) : null;
    $ime_klijenta = trim($_POST["ime_klijenta"]);
    $telefon_klijenta = !empty($_POST['telefon_klijenta']) ? trim($_POST['telefon_klijenta']) : null;
    $email_klijenta = !empty($_POST['email_klijenta']) ? trim($_POST['email_klijenta']) : null;
    $vrsta_vozila = trim($_POST["vrsta_vozila"]);
    $komitent_id = (int)$_POST["komitent_id"];
    $dodaci_vozilo = trim($_POST["dodaci_vozilo"]);
    $napomena = trim($_POST["napomena"]);
    $nacin_placanja = trim($_POST["placanje"] ?? '');
    $pdv_stopa = (int)($voznja['pdv_stopa'] ?? 10);
    if (isAdmin() && isset($_POST['pdv_stopa'])) {
        $pdv_stopa = (int)$_POST['pdv_stopa'];
        if (!in_array($pdv_stopa, [10, 20], true)) {
            $pdv_stopa = 10;
        }
    }
    $pdv_multiplier = 1 + ($pdv_stopa / 100);
    
    $cena = floatval($voznja['cena'] ?? 0);
    $cena_eur = $voznja['cena_eur'] ?? null;
    if (isAdmin()) {
        if ($_POST["cena"] ?? '' !== '') {
            $cena = floatval($_POST["cena"]);
        } elseif ($_POST["cena_bez_pdv"] ?? '' !== '') {
            $cena = floatval($_POST["cena_bez_pdv"]) * $pdv_multiplier;
        }
        
        $cena_eur = null;
        if ($_POST['cena_eur'] ?? '' !== '') {
            $cena_eur = floatval($_POST['cena_eur']);
        } elseif ($_POST['cena_eur_bez_pdv'] ?? '' !== '') {
            $cena_eur = floatval($_POST['cena_eur_bez_pdv']) * $pdv_multiplier;
        }
    }
    
    if (isAdmin()) {
        $vozac_id = !empty($_POST["vozac_id"]) ? (int)$_POST["vozac_id"] : null;
        $komitent_id = (int)$_POST["komitent_id"];
        $status = $voznja['status'];
        
        if ($vozac_id && ($status === 'Nerasporedjeno' || $status === 'Na čekanju')) {
            $status = 'Predstoji';
        } elseif (!$vozac_id && $status === 'Predstoji') {
            $status = 'Nerasporedjeno';
        }
    } else {
        $vozac_id = $voznja['vozac_id'];
        $komitent_id = $voznja['komitent_id'];
        $status = 'Na čekanju';
    }
    $troskovi = $voznja['troskovi'] ?? '';
    $komentar = $voznja['komentar'] ?? '';
    $tip_usluge = $_POST['tip_usluge'] ?? ($voznja['tip_usluge'] ?? 'transfer_od_do_adrese');
    $broj_sati = null;
    if ($tip_usluge === 'na_sat') {
        if (empty($_POST['broj_sati'])) {
            $error = "Molimo izaberite broj sati za uslugu na sat.";
        } else {
            $broj_sati = (int)$_POST['broj_sati'];
            if ($broj_sati < 3 || $broj_sati > 12) {
                $error = "Broj sati mora biti između 3 i 12.";
            }
        }
    } else {
        $broj_sati = null;
    }
    $attachment = $voznja['attachment'] ?? null;

    if (isAdmin() && isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        if (!empty($attachment) && file_exists(__DIR__ . '/' . $attachment)) {
            unlink(__DIR__ . '/' . $attachment);
        }
        
        $fileName = time() . '_' . basename($_FILES['attachment']['name']);
        $targetPath = $uploadDir . $fileName;
        
        $allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'application/msword', 
                         'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                         'application/vnd.ms-excel',
                         'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
        
        if (in_array($_FILES['attachment']['type'], $allowedTypes) && move_uploaded_file($_FILES['attachment']['tmp_name'], $targetPath)) {
            $attachment = 'uploads/' . $fileName;
        } else {
            $error = "Greška prilikom upload-a fajla. Dozvoljeni formati: PDF, slike, Word, Excel.";
        }
    }

    $empty_fields = [];
    if (empty($datum)) $empty_fields[] = "Datum";
    if (empty($vreme)) $empty_fields[] = "Vreme";
    if ($tip_usluge === 'transfer_od_do_adrese') {
        if (empty($polazna_adresa)) $empty_fields[] = "Polazna adresa";
        if (empty($dolazna_adresa)) $empty_fields[] = "Dolazna adresa";
    }
    if (empty($ime_klijenta)) $empty_fields[] = "Ime klijenta";
    if (empty($vrsta_vozila)) $empty_fields[] = "Vrsta vozila";
    if (empty($komitent_id)) $empty_fields[] = "Naručilac";

    if (!empty($empty_fields)) {
        $error = "Sledeća polja su obavezna: " . implode(", ", $empty_fields);
    } else {
        if (isAdmin() && isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
            $stmt = $conn->prepare("UPDATE voznje SET datum = ?, vreme = ?, broj_leta = ?, polazna_adresa = ?, polazna_place_id = ?, polazna_lat = ?, polazna_lng = ?, dolazna_adresa = ?, dolazna_place_id = ?, dolazna_lat = ?, dolazna_lng = ?, ime_klijenta = ?, telefon_klijenta = ?, email_klijenta = ?, vrsta_vozila = ?, komitent_id = ?, dodaci_vozilo = ?, napomena = ?, placanje = ?, pdv_stopa = ?, cena = ?, cena_eur = ?, vozac_id = ?, troskovi = ?, komentar = ?, status = ?, tip_usluge = ?, broj_sati = ?, attachment = ? WHERE id = ?");
            $stmt->bind_param("sssssddssddssssisssiddissssisi", $datum, $vreme, $broj_leta, $polazna_adresa, $polazna_place_id, $polazna_lat, $polazna_lng, $dolazna_adresa, $dolazna_place_id, $dolazna_lat, $dolazna_lng, $ime_klijenta, $telefon_klijenta, $email_klijenta, $vrsta_vozila, $komitent_id, $dodaci_vozilo, $napomena, $nacin_placanja, $pdv_stopa, $cena, $cena_eur, $vozac_id, $troskovi, $komentar, $status, $tip_usluge, $broj_sati, $attachment, $id);
        } else {
            if (isAdmin()) {
                $stmt = $conn->prepare("UPDATE voznje SET datum = ?, vreme = ?, broj_leta = ?, polazna_adresa = ?, polazna_place_id = ?, polazna_lat = ?, polazna_lng = ?, dolazna_adresa = ?, dolazna_place_id = ?, dolazna_lat = ?, dolazna_lng = ?, ime_klijenta = ?, telefon_klijenta = ?, email_klijenta = ?, vrsta_vozila = ?, komitent_id = ?, dodaci_vozilo = ?, napomena = ?, placanje = ?, pdv_stopa = ?, cena = ?, cena_eur = ?, vozac_id = ?, troskovi = ?, komentar = ?, status = ?, tip_usluge = ?, broj_sati = ? WHERE id = ?");
                $stmt->bind_param("sssssddssddssssisssiddissssii", $datum, $vreme, $broj_leta, $polazna_adresa, $polazna_place_id, $polazna_lat, $polazna_lng, $dolazna_adresa, $dolazna_place_id, $dolazna_lat, $dolazna_lng, $ime_klijenta, $telefon_klijenta, $email_klijenta, $vrsta_vozila, $komitent_id, $dodaci_vozilo, $napomena, $nacin_placanja, $pdv_stopa, $cena, $cena_eur, $vozac_id, $troskovi, $komentar, $status, $tip_usluge, $broj_sati, $id);
            } else {
                $stmt = $conn->prepare("UPDATE voznje SET datum = ?, vreme = ?, broj_leta = ?, polazna_adresa = ?, polazna_place_id = ?, polazna_lat = ?, polazna_lng = ?, dolazna_adresa = ?, dolazna_place_id = ?, dolazna_lat = ?, dolazna_lng = ?, ime_klijenta = ?, telefon_klijenta = ?, email_klijenta = ?, vrsta_vozila = ?, komitent_id = ?, dodaci_vozilo = ?, napomena = ?, placanje = ?, vozac_id = ?, troskovi = ?, komentar = ?, status = ?, tip_usluge = ?, broj_sati = ? WHERE id = ?");
                $stmt->bind_param("sssssddssddssssisssissssii", $datum, $vreme, $broj_leta, $polazna_adresa, $polazna_place_id, $polazna_lat, $polazna_lng, $dolazna_adresa, $dolazna_place_id, $dolazna_lat, $dolazna_lng, $ime_klijenta, $telefon_klijenta, $email_klijenta, $vrsta_vozila, $komitent_id, $dodaci_vozilo, $napomena, $nacin_placanja, $vozac_id, $troskovi, $komentar, $status, $tip_usluge, $broj_sati, $id);
            }
        }
        
        if ($stmt->execute()) {
            $success = true;
            
            if (isAdmin() && $vozac_id && $vozac_id != $voznja['vozac_id']) {
                $stmt = $conn->prepare("SELECT name, email FROM users WHERE id = ? AND role = 'vozac'");
                $stmt->bind_param("i", $vozac_id);
                $stmt->execute();
                $vozacResult = $stmt->get_result();
                
                if ($vozacRow = $vozacResult->fetch_assoc()) {
                    $vozac_ime = $vozacRow['name'];
                    $vozac_email = $vozacRow['email'];
                    
                    if (!empty($vozac_email)) {
                        $komitentName = '';
                        $stmt = $conn->prepare("SELECT naziv FROM komitenti WHERE id = ?");
                        $stmt->bind_param("i", $komitent_id);
                        $stmt->execute();
                        $komitentResult = $stmt->get_result();
                        if ($komitentRow = $komitentResult->fetch_assoc()) {
                            $komitentName = $komitentRow['naziv'];
                        }
                        
                        $tip_usluge_text = $tip_usluge === 'na_sat' ? 'Na sat' . (!empty($broj_sati) ? ' (' . $broj_sati . 'h)' : '') : 'Transfer od-do adrese';
                        
                        $subject = "Nova vožnja vam je dodeljena - " . date('d.m.Y', strtotime($datum)) . " " . date('H:i', strtotime($vreme));
                        
                        $body = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f4f4f4; margin: 0; padding: 0;">
    <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <div style="background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%); padding: 30px; text-align: center;">
            <img src="https://transfers.inf.rs/app/logo.png" alt="Royal Transport" style="max-width: 340px; height: auto; margin-bottom: 10px;">
            <h1 style="color: #ffffff; margin: 0; font-size: 24px;">Royal Transport</h1>
            <p style="color: #cccccc; margin: 10px 0 0 0; font-size: 14px;">Nova vožnja vam je dodeljena</p>
        </div>
        
        <div style="padding: 30px;">
            <p style="font-size: 16px; margin-top: 0;">Poštovani/a <strong>' . htmlspecialchars($vozac_ime) . '</strong>,</p>
            
            <div style="background-color: #e7f3ff; border-left: 4px solid #007bff; padding: 15px; margin: 20px 0; border-radius: 4px;">
                <p style="margin: 0; font-size: 16px; font-weight: bold; color: #007bff;">
                    Nova vožnja vam je dodeljena za <strong>' . date('d.m.Y', strtotime($datum)) . '</strong> u <strong>' . date('H:i', strtotime($vreme)) . '</strong>
                </p>
            </div>
            
            <div style="background-color: #f8f9fa; border-left: 4px solid #007bff; padding: 20px; margin: 20px 0; border-radius: 4px;">
                <h2 style="margin-top: 0; color: #007bff; font-size: 18px;">Detalji vožnje</h2>
                
                <table style="width: 100%; border-collapse: collapse;">';
                        
                        if (!empty($broj_leta)) {
                            $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; width: 140px; color: #555;">Broj leta:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($broj_leta) . '</td>
                    </tr>';
                        }
                        
                        $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Datum:</td>
                        <td style="padding: 8px 0; font-size: 16px; font-weight: bold; color: #007bff;">' . date('d.m.Y', strtotime($datum)) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Vreme:</td>
                        <td style="padding: 8px 0; font-size: 16px; font-weight: bold; color: #007bff;">' . date('H:i', strtotime($vreme)) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Klijent:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($ime_klijenta) . '</td>
                    </tr>';
                        
                        if ($tip_usluge === 'transfer_od_do_adrese') {
                            $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Polazak:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($polazna_adresa) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Destinacija:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($dolazna_adresa) . '</td>
                    </tr>';
                        } else {
                            $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Tip usluge:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($tip_usluge_text) . '</td>
                    </tr>';
                        }
                        
                        $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Vozilo:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($vrsta_vozila) . '</td>
                    </tr>';
                        
                        if (!empty($dodaci_vozilo)) {
                            $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Dodaci:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($dodaci_vozilo) . '</td>
                    </tr>';
                        }
                        
                        if (!empty($napomena)) {
                            $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Napomena:</td>
                        <td style="padding: 8px 0; font-style: italic; color: #666;">' . htmlspecialchars($napomena) . '</td>
                    </tr>';
                        }
                        
                        $body .= '
                </table>
            </div>
            
            <p style="color: #666; font-size: 14px; margin-top: 30px; margin-bottom: 0;">Hvala vam na pažnji!</p>
        </div>
        
        <div style="background-color: #f8f9fa; padding: 20px; text-align: center; border-top: 1px solid #dee2e6;">
            <p style="margin: 0; color: #6c757d; font-size: 12px;">Royal Transport &copy; ' . date('Y') . '</p>
        </div>
    </div>
</body>
</html>';
                        
                        if (sendEmail($vozac_email, $subject, $body, true)) {
                            error_log("Email poslat vozaču {$vozac_ime} ({$vozac_email}) za dodeljenu vožnju ID: {$id}");
                        } else {
                            error_log("Greška pri slanju emaila vozaču {$vozac_ime} ({$vozac_email}) za vožnju ID: {$id}");
                        }
                    }
                }
            }
            
            if (!isAdmin() && $voznja['status'] !== 'Na čekanju' && $voznja['status'] !== 'Odbijeno') {
                $stmt = $conn->prepare("SELECT email FROM users WHERE role = 'admin' LIMIT 1");
                $stmt->execute();
                $adminResult = $stmt->get_result();
                if ($adminRow = $adminResult->fetch_assoc()) {
                    $adminEmail = $adminRow['email'];
                    
                    $komitentName = '';
                    $stmt = $conn->prepare("SELECT naziv FROM komitenti WHERE id = ?");
                    $stmt->bind_param("i", $komitent_id);
                    $stmt->execute();
                    $komitentResult = $stmt->get_result();
                    if ($komitentRow = $komitentResult->fetch_assoc()) {
                        $komitentName = $komitentRow['naziv'];
                    }
                    
                    $userName = $_SESSION['user']['name'] ?? 'N/A';
                    
                    $subject = "Vožnja je izmenjena - zahtev za ponovno odobrenje - " . htmlspecialchars($komitentName) . " - " . htmlspecialchars($userName) . " - " . htmlspecialchars($broj_leta ?? 'N/A');
                    
                    $viewUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/pending_rides.php";
                    
                    $body = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f4f4f4; margin: 0; padding: 0;">
    <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <div style="background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%); padding: 30px; text-align: center;">
            <img src="https://transfers.inf.rs/app/logo.png" alt="Royal Transport" style="max-width: 340px; height: auto; margin-bottom: 10px;">
            <h1 style="color: #ffffff; margin: 0; font-size: 24px;">Royal Transport</h1>
            <p style="color: #cccccc; margin: 10px 0 0 0; font-size: 14px;">Vožnja je izmenjena</p>
        </div>
        
        <div style="padding: 30px;">
            <p style="font-size: 16px; margin-top: 0;">Poštovani administrator,</p>
            
            <div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px;">
                <p style="margin: 0; font-size: 16px; font-weight: bold; color: #856404;">
                    Vožnja je izmenjena od strane naručioca i vraćena je na status <strong>"Na čekanju"</strong>.
                </p>
            </div>
            
            <p>Molimo vas da pregledate izmene i ponovo odobrite vožnju.</p>
            
            <div style="background-color: #f8f9fa; border-left: 4px solid #007bff; padding: 20px; margin: 20px 0; border-radius: 4px;">
                <h2 style="margin-top: 0; color: #007bff; font-size: 18px;">Detalji vožnje</h2>
                
                <table style="width: 100%; border-collapse: collapse;">
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; width: 140px; color: #555;">Broj leta:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($broj_leta ?? 'N/A') . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Datum:</td>
                        <td style="padding: 8px 0;">' . date('d.m.Y', strtotime($datum)) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Vreme:</td>
                        <td style="padding: 8px 0;">' . date('H:i', strtotime($vreme)) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Naručilac:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($komitentName) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Klijent:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($ime_klijenta) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Polazna adresa:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($polazna_adresa) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Dolazna adresa:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($dolazna_adresa) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Vozilo:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($vrsta_vozila) . '</td>
                    </tr>';
                    
                    if (!empty($cena) && $cena > 0) {
                        $body .= '
                        <tr>
                            <td style="padding: 8px 0; font-weight: bold; color: #555;">Cena:</td>
                            <td style="padding: 8px 0; font-weight: bold; color: #28a745;">' . number_format(floatval($cena), 2, ',', '.') . ' RSD</td>
                        </tr>';
                    }
                    
                    $body .= '
                </table>
            </div>
            
            <div style="text-align: center; margin: 30px 0;">
                <a href="' . htmlspecialchars($viewUrl) . '" style="display: inline-block; background-color: #007bff; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 5px; font-weight: bold;">Pregledaj vožnju</a>
            </div>
            
            <p style="color: #666; font-size: 14px; margin-bottom: 0;">Hvala vam na pažnji!</p>
        </div>
        
        <div style="background-color: #f8f9fa; padding: 20px; text-align: center; border-top: 1px solid #dee2e6;">
            <p style="margin: 0; color: #6c757d; font-size: 12px;">Royal Transport &copy; ' . date('Y') . '</p>
        </div>
    </div>
</body>
</html>';
                    
                    if (shouldSendEmail('email_admin_ride_modified')) {
                        sendEmail($adminEmail, $subject, $body, true);
                    }
                }
            }
        } else {
            $error = "Greška prilikom ažuriranja vožnje.";
        }
    }
}

$stmt = $conn->prepare("SELECT id, naziv FROM komitenti ORDER BY naziv");
$stmt->execute();
$komitenti = $stmt->get_result();

$stmt = $conn->prepare("SELECT id, name FROM users WHERE role = 'vozac' ORDER BY name");
$stmt->execute();
$vozaci = $stmt->get_result();

$currentVrstaVozila = $voznja['vrsta_vozila'] ?? '';
$currentTipVozila = 'automobil';
if (in_array($currentVrstaVozila, $vrste_vozila_kombi)) {
    $currentTipVozila = 'kombi';
}
$currentTipUsluge = $voznja['tip_usluge'] ?? 'transfer_od_do_adrese';
$currentBrojSati = $voznja['broj_sati'] ?? null;

$placanjeOptions = $placanje;
$placanjeValue = $voznja['placanje'] ?? '';
$pdvStopaValue = (int)($voznja['pdv_stopa'] ?? 10);
$cenaBezPdvValue = '';
$cenaSaPdvValue = '';
$cenaEurBezPdvValue = '';
$cenaEurSaPdvValue = '';

if (isAdmin()) {
    $mult = 1 + ($pdvStopaValue / 100);
    $cenaSaPdvValue = ($voznja['cena'] ?? '') !== '' ? number_format(floatval($voznja['cena']), 2, '.', '') : '';
    $cenaBezPdvValue = ($voznja['cena'] ?? '') !== '' ? number_format(floatval($voznja['cena']) / $mult, 2, '.', '') : '';
    $cenaEurSaPdvValue = ($voznja['cena_eur'] ?? '') !== '' ? number_format(floatval($voznja['cena_eur']), 2, '.', '') : '';
    $cenaEurBezPdvValue = ($voznja['cena_eur'] ?? '') !== '' ? number_format(floatval($voznja['cena_eur']) / $mult, 2, '.', '') : '';
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $placanjeValue = $_POST['placanje'] ?? $placanjeValue;
    $pdvStopaValue = isset($_POST['pdv_stopa']) ? (int)$_POST['pdv_stopa'] : $pdvStopaValue;
    $cenaBezPdvValue = $_POST['cena_bez_pdv'] ?? $cenaBezPdvValue;
    $cenaSaPdvValue = $_POST['cena'] ?? $cenaSaPdvValue;
    $cenaEurBezPdvValue = $_POST['cena_eur_bez_pdv'] ?? $cenaEurBezPdvValue;
    $cenaEurSaPdvValue = $_POST['cena_eur'] ?? $cenaEurSaPdvValue;
}
?>

    <?php include "header.php"; ?>
    
    <script src="https://maps.googleapis.com/maps/api/js?key=<?php echo GOOGLE_PLACES_API_KEY; ?>&libraries=places&language=sr-Latn"></script>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <div class="card">
                    <div class="card-header">
                        <h2 class="mb-0">Izmena vožnje</h2>
                    </div>
                    <div class="card-body">
                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                Vožnja je uspešno ažurirana.
                                <a href="index.php" class="alert-link">Povratak na listu vožnji</a>
                            </div>
                        <?php else: ?>
                            <?php if ($error): ?>
                                <div class="alert alert-danger"><?php echo $error; ?></div>
                            <?php endif; ?>
                            
                            <?php if (!isAdmin() && $voznja['status'] !== 'Na čekanju' && $voznja['status'] !== 'Odbijeno'): ?>
                                <div class="alert alert-info alert-dismissible fade show">
                                    <i class="bi bi-info-circle me-2"></i>
                                    <strong>Važno:</strong> Ako izmenite podatke ove vožnje, status će se automatski vratiti na <strong>"Na čekanju"</strong> i administrator će dobiti notifikaciju za ponovno odobrenje. 
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            <?php endif; ?>

                            <form method="post" enctype="multipart/form-data">
                            <div class="row">
                            <div class="col-md-4 mb-3">
                                <div class="mb-4">
                                    <label class="form-label d-block fw-bold">Tip usluge</label>
                                    <div class="btn-group" role="group" aria-label="Tip usluge">
                                        <input type="radio" class="btn-check" name="tip_usluge" id="tip_transfer" value="transfer_od_do_adrese" <?php echo $currentTipUsluge === 'transfer_od_do_adrese' ? 'checked' : ''; ?>>
                                        <label class="btn btn-outline-secondary" for="tip_transfer">Transfer od/do adrese</label>
                                        
                                        <input type="radio" class="btn-check" name="tip_usluge" id="tip_na_sat" value="na_sat" <?php echo $currentTipUsluge === 'na_sat' ? 'checked' : ''; ?>>
                                        <label class="btn btn-outline-secondary" for="tip_na_sat">Na sat</label>
                                    </div>
                                </div>
                                </div>
                                <div class="col-md-8 mb-3">

                                <div id="broj_sati_group" class="mb-4" style="display: <?php echo $currentTipUsluge === 'na_sat' ? 'block' : 'none'; ?>;">
                                    <label class="form-label d-block fw-bold mb-2">Broj sati</label>
                                    <div class="btn-group flex-wrap" role="group" aria-label="Broj sati">
                                        <?php for ($i = 3; $i <= 12; $i++): ?>
                                        <input type="radio" class="btn-check" name="broj_sati" id="sati_<?php echo $i; ?>" value="<?php echo $i; ?>" <?php echo $currentBrojSati == $i ? 'checked' : ''; ?>>
                                        <label class="btn btn-outline-secondary" for="sati_<?php echo $i; ?>"><?php echo $i; ?>h</label>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="datum" class="form-label">Datum</label>
                                        <input type="date" class="form-control" id="datum" name="datum" value="<?php echo htmlspecialchars($voznja['datum']); ?>" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label for="vreme" class="form-label">Vreme</label>
                                        <input type="time" class="form-control" id="vreme" name="vreme" value="<?php echo htmlspecialchars($voznja['vreme']); ?>" required>
                                    </div>
                                    <div class="col-md-4 mb-3" id="broj_leta_group">
                                        <label for="broj_leta" class="form-label">Broj leta</label>
                                        <input type="text" class="form-control" id="broj_leta" name="broj_leta" value="<?php echo htmlspecialchars($voznja['broj_leta'] ?? ''); ?>">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Tip vozila</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="tip_vozila" id="tip_automobil" value="automobil" <?php echo $currentTipVozila === 'automobil' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="tip_automobil">
                                                Automobil
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="tip_vozila" id="tip_kombi" value="kombi" <?php echo $currentTipVozila === 'kombi' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="tip_kombi">
                                                Kombi
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="vrsta_vozila" class="form-label">Vrsta vozila</label>
                                        <select class="form-select" id="vrsta_vozila" name="vrsta_vozila" required>
                                            <option value="">Izaberi vrstu vozila</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="row" id="adrese_group">
                                    <div class="col-md-6 mb-3">
                                        <label for="polazna_adresa" class="form-label">Polazna adresa</label>
                                        <input type="text" class="form-control" id="polazna_adresa" name="polazna_adresa" value="<?php echo htmlspecialchars($voznja['polazna_adresa']); ?>" placeholder="Unesite polaznu adresu" required>
                                        <input type="hidden" id="polazna_place_id" name="polazna_place_id" value="<?php echo htmlspecialchars($voznja['polazna_place_id'] ?? ''); ?>">
                                        <input type="hidden" id="polazna_lat" name="polazna_lat" value="<?php echo htmlspecialchars($voznja['polazna_lat'] ?? ''); ?>">
                                        <input type="hidden" id="polazna_lng" name="polazna_lng" value="<?php echo htmlspecialchars($voznja['polazna_lng'] ?? ''); ?>">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="dolazna_adresa" class="form-label">Dolazna adresa</label>
                                        <input type="text" class="form-control" id="dolazna_adresa" name="dolazna_adresa" value="<?php echo htmlspecialchars($voznja['dolazna_adresa']); ?>" placeholder="Unesite dolaznu adresu" required>
                                        <input type="hidden" id="dolazna_place_id" name="dolazna_place_id" value="<?php echo htmlspecialchars($voznja['dolazna_place_id'] ?? ''); ?>">
                                        <input type="hidden" id="dolazna_lat" name="dolazna_lat" value="<?php echo htmlspecialchars($voznja['dolazna_lat'] ?? ''); ?>">
                                        <input type="hidden" id="dolazna_lng" name="dolazna_lng" value="<?php echo htmlspecialchars($voznja['dolazna_lng'] ?? ''); ?>">
                                    </div>

                                    <div class="col-12">
                                        <div id="distance_info" class="alert alert-info d-flex justify-content-between align-items-center" style="display: none;">
                                            <div><strong>Udaljenost:</strong></div>
                                            <div><span class="badge bg-primary" id="distance_value">0 km</span></div>
                                        </div>
                                        <div id="map" style="display: none; height: 320px; width: 100%; border-radius: 8px; border: 1px solid #dee2e6; margin-top: 15px;"></div>
                                    </div>
                                </div>

                                <div class="row mt-3">
                                    <div class="col-md-6 mb-3">
                                        <label for="ime_klijenta" class="form-label">Ime klijenta</label>
                                        <input type="text" class="form-control" id="ime_klijenta" name="ime_klijenta" value="<?php echo htmlspecialchars($voznja['ime_klijenta']); ?>" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="telefon_klijenta" class="form-label">Telefon klijenta</label>
                                        <input type="tel" class="form-control" id="telefon_klijenta" name="telefon_klijenta" value="<?php echo htmlspecialchars($voznja['telefon_klijenta'] ?? ''); ?>" placeholder="+381...">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="email_klijenta" class="form-label">Email klijenta</label>
                                        <input type="email" class="form-control" id="email_klijenta" name="email_klijenta" value="<?php echo htmlspecialchars($voznja['email_klijenta'] ?? ''); ?>" placeholder="klijent@example.com">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="komitent_id" class="form-label">Naručilac</label>
                                        <div class="input-group">
                                            <select class="form-select" id="komitent_id" name="komitent_id" required <?php echo !isAdmin() ? 'disabled' : ''; ?>>
                                                <?php if (isAdmin()): ?>
                                                    <option value="">Izaberi naručioca</option>
                                                    <?php while ($komitent = $komitenti->fetch_assoc()): ?>
                                                        <option value="<?php echo $komitent['id']; ?>" <?php echo $komitent['id'] == $voznja['komitent_id'] ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($komitent['naziv']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <?php 
                                                    $komitenti->data_seek(0);
                                                    while ($komitent = $komitenti->fetch_assoc()): 
                                                        if ($komitent['id'] == $_SESSION['user']['komitent_id']): ?>
                                                            <option value="<?php echo $komitent['id']; ?>" selected>
                                                                <?php echo htmlspecialchars($komitent['naziv']); ?>
                                                            </option>
                                                        <?php endif; ?>
                                                    <?php endwhile; ?>
                                                <?php endif; ?>
                                            </select>
                                            <?php if (isAdmin()): ?>
                                                <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#newKomitentModal">
                                                    <i class="bi bi-plus-lg"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                        <?php if (!isAdmin()): ?>
                                            <input type="hidden" name="komitent_id" value="<?php echo $_SESSION['user']['komitent_id']; ?>">
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="dodaci_vozilo" class="form-label">Dodaci za vozilo</label>
                                        <select class="form-select" id="dodaci_vozilo" name="dodaci_vozilo">
                                            <option value="">Izaberi dodatke</option>
                                            <?php foreach ($dodaci_vozilo as $dodatak): ?>
                                                <option value="<?php echo htmlspecialchars($dodatak); ?>" <?php echo $dodatak === $voznja['dodaci_vozilo'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($dodatak); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

                                    <?php if (isAdmin()): ?>
                                    <div class="col-md-6 mb-3">
                                        <label for="vozac_id" class="form-label">Vozač</label>
                                        <select class="form-select" id="vozac_id" name="vozac_id">
                                            <option value="">Izaberi vozača</option>
                                            <?php while ($vozac = $vozaci->fetch_assoc()): ?>
                                                <option value="<?php echo $vozac['id']; ?>" <?php echo $vozac['id'] == $voznja['vozac_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($vozac['name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                <?php endif; ?>
                                </div>

                                <?php include "payment_fields.php"; ?>



                                <div class="mb-3">
                                    <label for="napomena" class="form-label">Napomena</label>
                                    <textarea class="form-control" id="napomena" name="napomena" rows="3"><?php echo htmlspecialchars($voznja['napomena'] ?? ''); ?></textarea>
                                </div>

                                <?php if (isAdmin()): ?>
                                <div class="mb-3">
                                    <label for="attachment" class="form-label">Prilog (fajl)</label>
                                    <?php if (!empty($voznja['attachment'])): ?>
                                        <div class="mb-2">
                                            <a href="<?php echo htmlspecialchars($voznja['attachment'] ?? ''); ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                                <i class="bi bi-paperclip"></i> Trenutni fajl: <?php echo htmlspecialchars(basename($voznja['attachment'] ?? '')); ?>
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                    <input type="file" class="form-control" id="attachment" name="attachment" accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif">
                                    <div class="form-text">Dozvoljeni formati: PDF, Word, Excel, slike. Ostavite prazno da zadržite trenutni fajl.</div>
                                </div>
                                <?php endif; ?>

                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary"><i class="bi bi-floppy me-1"></i>Sačuvaj izmene</button>
                                    <a href="index.php" class="btn btn-secondary"><i class="bi bi-x-circle me-1"></i>Otkaži</a>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal za novog komitenta -->
    <div class="modal fade" id="newKomitentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Novi naručilac</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="newKomitentForm">
                        <div class="mb-3">
                            <label for="modal_naziv" class="form-label">Naziv</label>
                            <input type="text" class="form-control" id="modal_naziv" name="naziv" required>
                        </div>
                        <div class="mb-3">
                            <label for="modal_grad" class="form-label">Grad</label>
                            <input type="text" class="form-control" id="modal_grad" name="grad" required>
                        </div>
                        <div class="mb-3">
                            <label for="modal_adresa" class="form-label">Adresa</label>
                            <input type="text" class="form-control" id="modal_adresa" name="adresa">
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="modal_kontakt_osoba" class="form-label">Kontakt osoba</label>
                                <input type="text" class="form-control" id="modal_kontakt_osoba" name="kontakt_osoba">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="modal_email" class="form-label">Email adresa</label>
                                <input type="email" class="form-control" id="modal_email" name="email">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="modal_telefon" class="form-label">Kontakt telefon</label>
                                <input type="tel" class="form-control" id="modal_telefon" name="telefon">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="modal_pib" class="form-label">PIB</label>
                                <input type="text" class="form-control" id="modal_pib" name="pib">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="modal_maticni_broj" class="form-label">Matični broj</label>
                                <input type="text" class="form-control" id="modal_maticni_broj" name="maticni_broj">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="modal_cena_do_aerodroma" class="form-label">Cena do aerodroma</label>
                                <input type="number" step="0.01" class="form-control" id="modal_cena_do_aerodroma" name="cena_do_aerodroma" placeholder="0.00">
                                <div class="form-text">Cena u RSD</div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="modal_cena_od_aerodroma" class="form-label">Cena od aerodroma</label>
                                <input type="number" step="0.01" class="form-control" id="modal_cena_od_aerodroma" name="cena_od_aerodroma" placeholder="0.00">
                                <div class="form-text">Cena u RSD</div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Otkaži</button>
                    <button type="button" class="btn btn-primary" id="saveKomitent"><i class="bi bi-check-circle me-1"></i>Sačuvaj</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            $('#saveKomitent').click(function() {
                var formData = {
                    naziv: $('#modal_naziv').val(),
                    grad: $('#modal_grad').val(),
                    kontakt_osoba: $('#modal_kontakt_osoba').val() || '',
                    email: $('#modal_email').val() || '',
                    adresa: $('#modal_adresa').val() || '',
                    telefon: $('#modal_telefon').val() || '',
                    pib: $('#modal_pib').val() || '',
                    maticni_broj: $('#modal_maticni_broj').val() || '',
                    cena_do_aerodroma: $('#modal_cena_do_aerodroma').val() || '',
                    cena_od_aerodroma: $('#modal_cena_od_aerodroma').val() || ''
                };

                $.ajax({
                    url: 'create_komitent_ajax.php',
                    type: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.success) {
                            var newOption = new Option(response.komitent.naziv, response.komitent.id, true, true);
                            $('#komitent_id').append(newOption).trigger('change');
                            
                            var modal = bootstrap.Modal.getInstance($('#newKomitentModal'));
                            modal.hide();
                            $('body').removeClass('modal-open');
                            $('.modal-backdrop').remove();
                            $('#newKomitentForm')[0].reset();
                        } else {
                            alert('Greška: ' + response.error);
                        }
                    },
                    error: function() {
                        alert('Došlo je do greške prilikom čuvanja komitenta.');
                    }
                });
            });

            var updatingPrice = false;

            function getPdvMultiplier() {
                var pdv = parseFloat($('#pdv_stopa').val());
                if (isNaN(pdv)) {
                    pdv = 20;
                }
                return 1 + (pdv / 100);
            }

            function updatePdvLabels() {
                var pdv = parseFloat($('#pdv_stopa').val());
                if (isNaN(pdv)) {
                    pdv = 20;
                }
                $('.pdv_percent_text').text(pdv.toFixed(0) + '%');
            }

            function recalcPair(bezSelector, saSelector) {
                var bezEl = $(bezSelector);
                var saEl = $(saSelector);
                if (!bezEl.length || !saEl.length) {
                    return;
                }

                var mult = getPdvMultiplier();
                var bezRaw = bezEl.val();
                var saRaw = saEl.val();
                var bez = parseFloat(bezRaw);
                var sa = parseFloat(saRaw);

                if (bezRaw !== '' && !isNaN(bez)) {
                    saEl.val((bez * mult).toFixed(2));
                    return;
                }

                if (saRaw !== '' && !isNaN(sa)) {
                    bezEl.val((sa / mult).toFixed(2));
                }
            }

            $('#pdv_stopa').on('change', function() {
                if (updatingPrice) {
                    return;
                }
                updatingPrice = true;
                updatePdvLabels();
                recalcPair('#cena_bez_pdv', '#cena');
                recalcPair('#cena_eur_bez_pdv', '#cena_eur');
                updatingPrice = false;
            });

            $('#cena_bez_pdv').on('input', function() {
                if (updatingPrice) {
                    return;
                }
                updatingPrice = true;
                recalcPair('#cena_bez_pdv', '#cena');
                updatingPrice = false;
            });

            $('#cena').on('input', function() {
                if (updatingPrice) {
                    return;
                }
                updatingPrice = true;
                recalcPair('#cena_bez_pdv', '#cena');
                updatingPrice = false;
            });

            $('#cena_eur_bez_pdv').on('input', function() {
                if (updatingPrice) {
                    return;
                }
                updatingPrice = true;
                recalcPair('#cena_eur_bez_pdv', '#cena_eur');
                updatingPrice = false;
            });

            $('#cena_eur').on('input', function() {
                if (updatingPrice) {
                    return;
                }
                updatingPrice = true;
                recalcPair('#cena_eur_bez_pdv', '#cena_eur');
                updatingPrice = false;
            });

            updatePdvLabels();
            recalcPair('#cena_bez_pdv', '#cena');
            recalcPair('#cena_eur_bez_pdv', '#cena_eur');

            var automobilOptions = [
                <?php foreach ($vrste_vozila_automobil as $vrsta): ?>
                    { value: '<?php echo htmlspecialchars($vrsta); ?>', text: '<?php echo htmlspecialchars($vrsta); ?>' },
                <?php endforeach; ?>
            ];
            
            var kombiOptions = [
                <?php foreach ($vrste_vozila_kombi as $vrsta): ?>
                    { value: '<?php echo htmlspecialchars($vrsta); ?>', text: '<?php echo htmlspecialchars($vrsta); ?>' },
                <?php endforeach; ?>
            ];

            function updateVrstaVozilaOptions() {
                var tipVozila = $('input[name="tip_vozila"]:checked').val();
                var select = $('#vrsta_vozila');
                var currentValue = select.val() || '<?php echo htmlspecialchars($voznja['vrsta_vozila'] ?? ''); ?>';
                
                select.find('option').not(':first').remove();
                
                var optionsToAdd = tipVozila === 'automobil' ? automobilOptions : kombiOptions;
                optionsToAdd.forEach(function(option) {
                    var optionElement = $('<option></option>')
                        .attr('value', option.value)
                        .text(option.text);
                    select.append(optionElement);
                });
                
                if (currentValue && select.find('option[value="' + currentValue + '"]').length) {
                    select.val(currentValue);
                } else {
                    select.val('');
                }
            }
            
            $('input[name="tip_vozila"]').on('change', function() {
                updateVrstaVozilaOptions();
            });
            
            updateVrstaVozilaOptions();

            function toggleTipUslugeFields() {
                var tipUsluge = $('input[name="tip_usluge"]:checked').val();
                var brojSatiGroup = $('#broj_sati_group');
                var adreseGroup = $('#adrese_group');
                
                if (tipUsluge === 'na_sat') {
                    brojSatiGroup.show();
                    adreseGroup.find('input').prop('required', false);
                    hideRoute();
                } else {
                    brojSatiGroup.hide();
                    $('input[name="broj_sati"]').prop('checked', false);
                    adreseGroup.find('input').prop('required', true);
                    calculateRoute();
                }
            }

            $('input[name="tip_usluge"]').on('change', function() {
                toggleTipUslugeFields();
            });

            $('form').on('submit', function(e) {
                var tipUsluge = $('input[name="tip_usluge"]:checked').val();
                if (tipUsluge === 'na_sat') {
                    if (!$('input[name="broj_sati"]:checked').length) {
                        e.preventDefault();
                        alert('Molimo izaberite broj sati za uslugu na sat.');
                        return false;
                    }
                }
            });

            toggleTipUslugeFields();

            var map;
            var directionsService;
            var directionsRenderer;
            var polaznaPlace = null;
            var dolaznaPlace = null;
            var polaznaInputEl = null;
            var dolaznaInputEl = null;
            var polaznaPlaceIdEl = null;
            var dolaznaPlaceIdEl = null;
            var polaznaLatEl = null;
            var polaznaLngEl = null;
            var dolaznaLatEl = null;
            var dolaznaLngEl = null;
            var polaznaSelectedValue = '';
            var dolaznaSelectedValue = '';

            function hideRoute() {
                $('#distance_info').hide();
                $('#map').hide();
                if (directionsRenderer) {
                    directionsRenderer.set('directions', null);
                }
            }

            function calculateRoute() {
                var tipUsluge = $('input[name="tip_usluge"]:checked').val();
                if (tipUsluge !== 'transfer_od_do_adrese') {
                    hideRoute();
                    return;
                }

                var origin = null;
                var destination = null;
                if (polaznaPlace && polaznaPlace.geometry) {
                    origin = polaznaPlace.geometry.location;
                } else if (polaznaLatEl && polaznaLngEl && polaznaLatEl.value && polaznaLngEl.value) {
                    origin = new google.maps.LatLng(parseFloat(polaznaLatEl.value), parseFloat(polaznaLngEl.value));
                }

                if (dolaznaPlace && dolaznaPlace.geometry) {
                    destination = dolaznaPlace.geometry.location;
                } else if (dolaznaLatEl && dolaznaLngEl && dolaznaLatEl.value && dolaznaLngEl.value) {
                    destination = new google.maps.LatLng(parseFloat(dolaznaLatEl.value), parseFloat(dolaznaLngEl.value));
                }

                if (!origin || !destination) {
                    hideRoute();
                    return;
                }

                var request = {
                    origin: origin,
                    destination: destination,
                    travelMode: google.maps.TravelMode.DRIVING
                };

                directionsService.route(request, function(result, status) {
                    if (status === google.maps.DirectionsStatus.OK) {
                        directionsRenderer.setDirections(result);
                        var route = result.routes[0];
                        var distanceMeters = 0;
                        for (var i = 0; i < route.legs.length; i++) {
                            distanceMeters += route.legs[i].distance.value;
                        }
                        var distanceKm = (distanceMeters / 1000).toFixed(1);
                        $('#distance_value').text(distanceKm + ' km');
                        $('#distance_info').fadeIn();
                        $('#map').fadeIn();
                    } else {
                        hideRoute();
                    }
                });
            }

            function initAddressAutocomplete() {
                var serbiaBounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(41.855416, 18.817020),
                    new google.maps.LatLng(46.181389, 23.004997)
                );

                polaznaInputEl = document.getElementById('polazna_adresa');
                dolaznaInputEl = document.getElementById('dolazna_adresa');
                polaznaPlaceIdEl = document.getElementById('polazna_place_id');
                dolaznaPlaceIdEl = document.getElementById('dolazna_place_id');
                polaznaLatEl = document.getElementById('polazna_lat');
                polaznaLngEl = document.getElementById('polazna_lng');
                dolaznaLatEl = document.getElementById('dolazna_lat');
                dolaznaLngEl = document.getElementById('dolazna_lng');
                polaznaSelectedValue = polaznaInputEl ? polaznaInputEl.value : '';
                dolaznaSelectedValue = dolaznaInputEl ? dolaznaInputEl.value : '';

                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 7,
                    center: { lat: 44.787197, lng: 20.457273 }
                });

                directionsService = new google.maps.DirectionsService();
                directionsRenderer = new google.maps.DirectionsRenderer({
                    map: map,
                    suppressMarkers: false
                });

                var polaznaAutocomplete = new google.maps.places.Autocomplete(polaznaInputEl, {
                    componentRestrictions: { country: 'rs' },
                    bounds: serbiaBounds,
                    strictBounds: true
                });

                var dolaznaAutocomplete = new google.maps.places.Autocomplete(dolaznaInputEl, {
                    componentRestrictions: { country: 'rs' },
                    bounds: serbiaBounds,
                    strictBounds: true
                });

                polaznaAutocomplete.addListener('place_changed', function() {
                    var place = polaznaAutocomplete.getPlace();
                    if (place.geometry && place.formatted_address) {
                        polaznaInputEl.value = place.formatted_address;
                        polaznaPlace = place;
                        polaznaSelectedValue = place.formatted_address;
                        if (polaznaPlaceIdEl) polaznaPlaceIdEl.value = place.place_id || '';
                        if (polaznaLatEl) polaznaLatEl.value = place.geometry.location.lat();
                        if (polaznaLngEl) polaznaLngEl.value = place.geometry.location.lng();
                        calculateRoute();
                    }
                });

                dolaznaAutocomplete.addListener('place_changed', function() {
                    var place = dolaznaAutocomplete.getPlace();
                    if (place.geometry && place.formatted_address) {
                        dolaznaInputEl.value = place.formatted_address;
                        dolaznaPlace = place;
                        dolaznaSelectedValue = place.formatted_address;
                        if (dolaznaPlaceIdEl) dolaznaPlaceIdEl.value = place.place_id || '';
                        if (dolaznaLatEl) dolaznaLatEl.value = place.geometry.location.lat();
                        if (dolaznaLngEl) dolaznaLngEl.value = place.geometry.location.lng();
                        calculateRoute();
                    }
                });

                polaznaInputEl.placeholder = 'Unesite polaznu adresu';
                dolaznaInputEl.placeholder = 'Unesite dolaznu adresu';

                $(polaznaInputEl).on('input', function() {
                    if (this.value !== polaznaSelectedValue) {
                        polaznaSelectedValue = '';
                        polaznaPlace = null;
                        if (polaznaPlaceIdEl) polaznaPlaceIdEl.value = '';
                        if (polaznaLatEl) polaznaLatEl.value = '';
                        if (polaznaLngEl) polaznaLngEl.value = '';
                        hideRoute();
                    }
                });

                $(dolaznaInputEl).on('input', function() {
                    if (this.value !== dolaznaSelectedValue) {
                        dolaznaSelectedValue = '';
                        dolaznaPlace = null;
                        if (dolaznaPlaceIdEl) dolaznaPlaceIdEl.value = '';
                        if (dolaznaLatEl) dolaznaLatEl.value = '';
                        if (dolaznaLngEl) dolaznaLngEl.value = '';
                        hideRoute();
                    }
                });

                calculateRoute();
            }

            if (typeof google !== 'undefined' && google.maps && google.maps.places) {
                initAddressAutocomplete();
            } else {
                window.addEventListener('load', function() {
                    if (typeof google !== 'undefined' && google.maps && google.maps.places) {
                        initAddressAutocomplete();
                    }
                });
            }
        });
    </script>
    <?php include 'footer.php'; ?> 