<?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;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $broj_leta = $_POST['broj_leta'];
    $datum = $_POST['datum'];
    $vreme = $_POST['vreme'];
    $vrsta_vozila = $_POST['vrsta_vozila'];
    $dodaci_vozilo = $_POST['dodaci_vozilo'];
    $vozac_id = !empty($_POST['vozac_id']) ? (int)$_POST['vozac_id'] : null;
    $ime_klijenta = $_POST['ime_klijenta'];
    $polazna_adresa = $_POST['polazna_adresa'];
    $dolazna_adresa = $_POST['dolazna_adresa'];
    $komitent_id = $_POST['komitent_id'];
    
    if (!empty($_POST['cena'])) {
        $cena = floatval($_POST['cena']);
    } elseif (!empty($_POST['cena_bez_pdv'])) {
        $cena = floatval($_POST['cena_bez_pdv']) * 1.20;
    } else {
        $cena = 0.0;
    }
    
    $placanje = $_POST['placanje'];
    $napomena = $_POST['napomena'];
    $tip_usluge = $_POST['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.";
            }
        }
    }
    $attachment = null;
    
    if (isAdmin() && isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $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.";
        }
    }
    
    if (isAdmin()) {
        $status = $vozac_id ? 'Predstoji' : getDefaultRideStatus();
    } else {
        $status = 'Na čekanju';
        $vozac_id = null;
    }

    $sql = "INSERT INTO voznje (broj_leta, datum, vreme, vrsta_vozila, dodaci_vozilo, vozac_id, ime_klijenta, 
            polazna_adresa, dolazna_adresa, komitent_id, cena, placanje, napomena, status, tip_usluge, broj_sati, attachment) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssssissssdsssssi", 
        $broj_leta, 
        $datum, 
        $vreme, 
        $vrsta_vozila, 
        $dodaci_vozilo, 
        $vozac_id, 
        $ime_klijenta, 
        $polazna_adresa, 
        $dolazna_adresa, 
        $komitent_id, 
        $cena, 
        $placanje, 
        $napomena, 
        $status,
        $tip_usluge,
        $broj_sati,
        $attachment
    );
        
    if ($stmt->execute()) {
        $success = true;
        
        if (!isAdmin()) {
            $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 = "Nova vožnja na čekanju - " . 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;">Nova vožnja na čekanju</p>
        </div>
        
        <div style="padding: 30px;">
            <p style="font-size: 16px; margin-top: 0;">Poštovani administrator,</p>
            <p>Nova vožnja je kreirana i čeka na vašu potvrdu.</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_new_ride')) {
                    sendEmail($adminEmail, $subject, $body, true);
                }
            }
        }
    } else {
        $error = "Greška prilikom kreiranja 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();
?>

    <?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 justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title mb-0">Nova vožnja</h3>
                    </div>
                    <div class="card-body">
        <?php if ($success): ?>
            <div class="alert alert-success">
                <?php if (!isAdmin()): ?>
                    Vožnja je uspešno kreirana i stavljena na čekanje. Administrator će vas obavestiti kada bude potvrđena.
                <?php else: ?>
                    Vožnja je uspešno kreirana.
                <?php endif; ?>
                <a href="index.php" class="alert-link">Povratak na listu vožnji</a>
            </div>
                        <?php elseif ($error): ?>
                            <div class="alert alert-danger">
                                <?php echo htmlspecialchars($error); ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!$success): ?>
                            <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" checked>
                                        <label class="btn btn-outline-dark" for="tip_transfer">Od/do adrese</label>
                                        
                                        <input type="radio" class="btn-check" name="tip_usluge" id="tip_na_sat" value="na_sat">
                                        <label class="btn btn-outline-dark" 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: 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; ?>">
                                        <label class="btn btn-outline-dark" for="sati_<?php echo $i; ?>"><?php echo $i; ?>h</label>
                                        <?php endfor; ?>
                                    </div>
                                </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" 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" 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">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label d-block">Tip vozila</label>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="tip_vozila" id="tip_automobil" value="automobil" checked>
                                            <label class="form-check-label" for="tip_automobil">
                                                Automobil
                                            </label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="tip_vozila" id="tip_kombi" value="kombi">
                                            <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" placeholder="Unesite polaznu adresu" required>
                                    </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" placeholder="Unesite dolaznu adresu" required>
                                    </div>
                                </div>

                                <div class="row">
                                    <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" required>
                                    </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 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 htmlspecialchars($dodatak); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="placanje" class="form-label">Plaćanje</label>
                                        <select class="form-select" id="placanje" name="placanje">
                                            <option value="">Izaberi način plaćanja</option>
                                            <?php foreach ($placanje as $nacin): ?>
                                                <option value="<?php echo htmlspecialchars($nacin); ?>">
                                                    <?php echo htmlspecialchars($nacin); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>

                                <?php if (isAdmin()): ?>
                                <div class="row">
                                    <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 htmlspecialchars($vozac['name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label for="cena_bez_pdv" class="form-label">Cena bez PDV-a</label>
                                        <input type="number" step="0.01" class="form-control" id="cena_bez_pdv" name="cena_bez_pdv" placeholder="0.00">
                                        <div class="form-text">Cena u RSD</div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label for="cena" class="form-label">Cena sa PDV-om</label>
                                        <input type="number" step="0.01" class="form-control" id="cena" name="cena" placeholder="0.00">
                                        <div class="form-text">Cena u RSD</div>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <div class="mb-3">
                                    <label for="napomena" class="form-label">Napomena</label>
                                    <textarea class="form-control" id="napomena" name="napomena" rows="3"></textarea>
                                </div>

                                <?php if (isAdmin()): ?>
                                <div class="mb-3">
                                    <label for="attachment" class="form-label">Prilog (fajl)</label>
                                    <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</div>
                                </div>
                                <?php endif; ?>

                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary"><i class="bi bi-plus-circle me-1"></i>Kreiraj vožnju</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;
            
            $('#cena_bez_pdv').on('input', function() {
                if (!updatingPrice) {
                    updatingPrice = true;
                    var cenaBezPDV = parseFloat($(this).val()) || 0;
                    var cenaSaPDV = cenaBezPDV * 1.20;
                    $('#cena').val(cenaSaPDV.toFixed(2));
                    updatingPrice = false;
                }
            });

            $('#cena').on('input', function() {
                if (!updatingPrice) {
                    updatingPrice = true;
                    var cenaSaPDV = parseFloat($(this).val()) || 0;
                    var cenaBezPDV = cenaSaPDV / 1.20;
                    $('#cena_bez_pdv').val(cenaBezPDV.toFixed(2));
                    updatingPrice = false;
                }
            });

            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();
                
                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');
                var brojLetGroup = $('#broj_leta_group');
                
                if (tipUsluge === 'na_sat') {
                    brojSatiGroup.show();
                    adreseGroup.find('input').prop('required', false);
                    brojLetGroup.hide();
                } else {
                    brojSatiGroup.hide();
                    $('input[name="broj_sati"]').prop('checked', false);
                    adreseGroup.find('input').prop('required', true);
                    brojLetGroup.show();
                }
            }

            $('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();

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

                var polaznaInput = document.getElementById('polazna_adresa');
                var dolaznaInput = document.getElementById('dolazna_adresa');

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

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

                polaznaAutocomplete.addListener('place_changed', function() {
                    var place = polaznaAutocomplete.getPlace();
                    if (place.formatted_address) {
                        polaznaInput.value = place.formatted_address;
                    }
                });

                dolaznaAutocomplete.addListener('place_changed', function() {
                    var place = dolaznaAutocomplete.getPlace();
                    if (place.formatted_address) {
                        dolaznaInput.value = place.formatted_address;
                    }
                });

                polaznaInput.placeholder = 'Unesite polaznu adresu';
                dolaznaInput.placeholder = 'Unesite dolaznu adresu';
            }

            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'; ?> 