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

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

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

if (!isAdmin() && ($_SESSION['user']['role'] ?? null) === 'vozac') {
    $stmt = $conn->prepare("SELECT id FROM voznje WHERE id = ? AND vozac_id = ?");
    $stmt->bind_param("ii", $id, $_SESSION['user']['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        header("Location: index.php");
        exit();
    }
}

$sql = "SELECT v.*, k.naziv as komitent_naziv, u.name as vozac_ime, u.telefon as vozac_telefon 
        FROM voznje v 
        LEFT JOIN komitenti k ON v.komitent_id = k.id 
        LEFT JOIN users u ON v.vozac_id = u.id 
        WHERE v.id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$voznja = $result->fetch_assoc();

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

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

function statusToCssClass($status) {
    // transliteracija UTF-8 -> ASCII
    $ascii = iconv('UTF-8', 'ASCII//TRANSLIT', $status);

    // ako iconv ne uspe, pada fallback
    if ($ascii === false) {
        $ascii = $status;
    }

    // u lowercase
    $ascii = strtolower($ascii);

    // zamena specifičnih slova i razmaci -> crtica
    $ascii = str_replace(
        [' ', 'č', 'ć', 'š', 'ž', 'đ', 'Č', 'Ć', 'Š', 'Ž', 'Đ'],
        ['-', 'c', 'c', 's', 'z', 'd', 'c', 'c', 's', 'z', 'd'],
        $ascii
    );

    return $ascii;
}

function getFlightTrackingLinks($flightNumber) {
    if (empty($flightNumber)) {
        return null;
    }
    
    $flightNumber = strtoupper(trim($flightNumber));
    $encodedFlight = urlencode($flightNumber);
    
    $airlineCode = '';
    $flightNum = '';
    
    if (preg_match('/^([A-Z]{2,3})(\d+)$/', $flightNumber, $matches)) {
        $airlineCode = $matches[1];
        $flightNum = $matches[2];
    }
    
    $flightstatsUrl = "https://www.flightstats.com/v2/flight-tracker/{$encodedFlight}";
    if ($airlineCode && $flightNum) {
        $flightstatsUrl = "https://www.flightstats.com/v2/flight-tracker/{$airlineCode}/{$flightNum}";
    }
    
    return [
        'flightradar24' => "https://www.flightradar24.com/{$encodedFlight}",
        'flightstats' => $flightstatsUrl
    ];
}

$flightLinks = getFlightTrackingLinks($voznja['broj_leta']);

$dokumenti = [];
$stmt_docs = $conn->prepare("SELECT d.*, u.name as uploader_name FROM dokumenti d LEFT JOIN users u ON d.uploaded_by = u.id WHERE d.voznja_id = ? AND d.tip = 'zavrsenje_voznje' ORDER BY d.vreme DESC");
$stmt_docs->bind_param("i", $id);
$stmt_docs->execute();
$result_docs = $stmt_docs->get_result();
while ($doc = $result_docs->fetch_assoc()) {
    $dokumenti[] = $doc;
}
?>

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

<?php if (($voznja['tip_usluge'] ?? 'transfer_od_do_adrese') === 'transfer_od_do_adrese' && (!empty($voznja['polazna_adresa']) || !empty($voznja['polazna_lat'])) && (!empty($voznja['dolazna_adresa']) || !empty($voznja['dolazna_lat']))): ?>
<script src="https://maps.googleapis.com/maps/api/js?key=<?php echo GOOGLE_PLACES_API_KEY; ?>&libraries=places&language=sr-Latn"></script>
<?php endif; ?>

<div class="container mt-4">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-center mb-4">
        <h2>Pregled vožnje #<?php echo htmlspecialchars($voznja['broj_leta'] ?? ''); ?></h2>
        <span class="status-badge badge bg-danger text-white status-<?php echo statusToCssClass($voznja['status']); ?>">
            <?php echo htmlspecialchars($voznja['status']); ?>
        </span>
    </div>

    <div class="row g-4">
        <?php if ($flightLinks && !empty($voznja['broj_leta'])): ?>
        <!-- Detalji leta -->
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-airplane me-2"></i>
                        Detalji leta: <?php echo htmlspecialchars($voznja['broj_leta']); ?>
                    </h5>
                </div>
                <div class="card-body">
                    <p class="text-muted mb-3">Pratite detalje leta na sledećim stranicama:</p>
                    <div class="btn-group w-100" role="group">
                        <a href="<?php echo htmlspecialchars($flightLinks['flightradar24']); ?>" 
                           target="_blank" 
                           rel="noopener noreferrer"
                           class="btn btn-outline-dark">
                            <i class="bi bi-globe me-2"></i>
                            FlightRadar24
                        </a>
                        <a href="<?php echo htmlspecialchars($flightLinks['flightstats']); ?>" 
                           target="_blank" 
                           rel="noopener noreferrer"
                           class="btn btn-outline-dark">
                            <i class="bi bi-globe me-2"></i>
                            FlightStats
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Osnovne informacije -->
        <div class="col-md-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-calendar-event me-2"></i>
                        Osnovne informacije
                    </h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label text-muted">Datum i vreme</label>
                        <p class="mb-0">
                            <?php echo date('d.m.Y', strtotime($voznja['datum'])); ?> 
                            <?php echo date('H:i', strtotime($voznja['vreme'])); ?>
                        </p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted">Vozilo</label>
                        <p class="mb-0"><?php echo htmlspecialchars($voznja['vrsta_vozila'] ?? ''); ?></p>
                    </div>
                    <?php if (!empty($voznja['dodaci_vozilo'])): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Dodaci</label>
                        <p class="mb-0"><?php echo htmlspecialchars($voznja['dodaci_vozilo']); ?></p>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($voznja['broj_leta'])): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Broj leta</label>
                        <p class="mb-0">
                            <strong><?php echo htmlspecialchars($voznja['broj_leta']); ?></strong>
                        </p>
                    </div>
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Tip usluge</label>
                        <p class="mb-0">
                            <?php 
                            $tip_usluge = $voznja['tip_usluge'] ?? 'transfer_od_do_adrese';
                            if ($tip_usluge === 'na_sat'): 
                                $broj_sati = $voznja['broj_sati'] ?? null;
                            ?>
                                <span class="badge bg-info">Na sat</span>
                                <?php if ($broj_sati): ?>
                                    <span class="badge bg-secondary ms-2"><?php echo $broj_sati; ?>h</span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="badge bg-primary">Transfer od/do adrese</span>
                            <?php endif; ?>
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Informacije o klijentu -->
        <div class="col-md-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-people me-2"></i>
                        Informacije o klijentu
                    </h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label text-muted">Klijent</label>
                        <p class="mb-0"><?php echo htmlspecialchars($voznja['ime_klijenta'] ?? ''); ?></p>
                    </div>
                    <?php if (!isAdmin() && $_SESSION['user']['role'] !== 'vozac'): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Naručilac</label>
                        <p class="mb-0"><?php echo htmlspecialchars($voznja['komitent_naziv'] ?? ''); ?></p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php 
        $tip_usluge = $voznja['tip_usluge'] ?? 'transfer_od_do_adrese';
        if ($tip_usluge === 'transfer_od_do_adrese'): ?>
        <!-- Lokacije -->
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-geo-alt me-2"></i>
                        Lokacije
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted">Polazna adresa</label>
                                <p class="mb-0"><?php echo htmlspecialchars($voznja['polazna_adresa'] ?? ''); ?></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted">Dolazna adresa</label>
                                <p class="mb-0"><?php echo htmlspecialchars($voznja['dolazna_adresa'] ?? ''); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if (!empty($voznja['polazna_adresa']) && !empty($voznja['dolazna_adresa'])): ?>
        <!-- Mapa rute -->
        <div class="col-md-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-map me-2"></i>
                        Ruta
                    </h5>
                    <span class="badge bg-primary fs-6" id="route_distance_badge" style="display:none;"></span>
                </div>
                <div class="card-body p-0">
                    <div id="route_map" style="height: 380px; width: 100%;"></div>
                    <?php
                    if (!isAdmin() && ($_SESSION['user']['role'] ?? null) === 'vozac') {
                        if (!empty($voznja['dolazna_lat']) && !empty($voznja['dolazna_lng'])) {
                            $mapsDestination = urlencode($voznja['dolazna_lat'] . ',' . $voznja['dolazna_lng']);
                        } else {
                            $mapsDestination = urlencode($voznja['dolazna_adresa']);
                        }
                        $mapsUrl = 'https://www.google.com/maps/dir/?api=1&travelmode=driving&destination=' . $mapsDestination;
                    ?>
                    <a href="<?php echo htmlspecialchars($mapsUrl); ?>" target="_blank" rel="noopener noreferrer" class="btn btn-primary btn-lg w-100" style="border-radius: 0 0 8px 8px;">
                        <i class="bi bi-compass me-2"></i>Kreni
                    </a>
                    <?php } ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php endif; ?>

        <?php if (!isAdmin() && $_SESSION['user']['role'] !== 'vozac'): ?>
        <!-- Finansije -->
        <div class="col-md-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-credit-card me-2"></i>
                        Finansije
                    </h5>
                </div>
                <div class="card-body">
                    <?php
                    $pdv_stopa = (int)($voznja['pdv_stopa'] ?? 10);
                    if (!in_array($pdv_stopa, [10, 20], true)) {
                        $pdv_stopa = 10;
                    }
                    $pdv_multiplier = 1 + ($pdv_stopa / 100);
                    ?>
                    <?php if (!empty($voznja['cena'])): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Cena bez PDV-a</label>
                        <p class="mb-0"><?php echo number_format(floatval($voznja['cena']) / $pdv_multiplier, 2, ',', '.'); ?> RSD</p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted">Cena sa PDV-om (<?php echo htmlspecialchars((string)$pdv_stopa); ?>%)</label>
                        <p class="mb-0"><strong><?php echo number_format(floatval($voznja['cena']), 2, ',', '.'); ?> RSD</strong></p>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($voznja['cena_eur'])): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Cena bez PDV-a</label>
                        <p class="mb-0"><?php echo number_format(floatval($voznja['cena_eur']) / $pdv_multiplier, 2, ',', '.'); ?> EUR</p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted">Cena sa PDV-om (<?php echo htmlspecialchars((string)$pdv_stopa); ?>%)</label>
                        <p class="mb-0"><strong><?php echo number_format(floatval($voznja['cena_eur']), 2, ',', '.'); ?> EUR</strong></p>
                    </div>
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Način plaćanja</label>
                        <p class="mb-0"><?php echo htmlspecialchars($voznja['placanje'] ?? ''); ?></p>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Dodatne informacije -->
        <div class="col-md-<?php echo (!isAdmin() && $_SESSION['user']['role'] !== 'vozac') ? '6' : '12'; ?> mb-3 mb-md-0">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-chat-left-text me-2"></i>
                        Dodatne informacije
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($voznja['napomena'])): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Napomena</label>
                        <p class="mb-0"><?php echo htmlspecialchars($voznja['napomena']); ?></p>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($voznja['troskovi'])): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Napomena o dodatnim troškovima</label>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($voznja['troskovi'])); ?></p>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($voznja['komentar'])): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Napomena o vožnji i putnicima</label>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($voznja['komentar'])); ?></p>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($voznja['attachment'])): ?>
                    <div class="mb-3">
                        <label class="form-label text-muted">Prilog</label>
                        <p class="mb-0">
                            <a href="<?php echo htmlspecialchars($voznja['attachment']); ?>" target="_blank" class="btn btn-outline-primary">
                                <i class="bi bi-paperclip me-2"></i>
                                <?php echo htmlspecialchars(basename($voznja['attachment'])); ?>
                            </a>
                        </p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if (!empty($dokumenti)): ?>
        <!-- Dokumenti prilikom završetka vožnje -->
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-files me-2"></i>
                        Dokumenti prilikom završetka vožnje
                    </h5>
                </div>
                <div class="card-body">
                    <div class="list-group">
                        <?php foreach ($dokumenti as $doc): ?>
                        <div class="list-group-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <i class="bi bi-paperclip me-2"></i>
                                    <a href="<?php echo htmlspecialchars($doc['putanja']); ?>" target="_blank" class="text-decoration-none fw-bold">
                                        <?php echo htmlspecialchars($doc['naziv_fajla']); ?>
                                    </a>
                                    <small class="text-muted ms-2">
                                        (<?php echo number_format($doc['velicina_fajla'] / 1024, 2); ?> KB)
                                    </small>
                                </div>
                                <div class="text-end">
                                    <small class="text-muted d-block">
                                        Uploadovao: <?php echo htmlspecialchars($doc['uploader_name'] ?? 'N/A'); ?>
                                    </small>
                                    <small class="text-muted">
                                        <?php echo date('d.m.Y H:i', strtotime($doc['vreme'])); ?>
                                    </small>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if (!isAdmin() && ($_SESSION['user']['role'] ?? null) === 'vozac'): ?>
<button type="button" class="btn btn-success btn-lg sticky-bottom-left" id="showClientName">
    <i class="bi bi-person-badge me-2"></i>Ime klijenta
</button>

<div class="client-name-overlay" id="clientNameOverlay" aria-hidden="true">
    <button type="button" class="btn btn-light client-name-close" id="clientNameClose" aria-label="Zatvori">&times;</button>
    <div class="client-name-text">
        <?php echo htmlspecialchars($voznja['ime_klijenta'] ?? ''); ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const btn = document.getElementById('showClientName');
    const overlay = document.getElementById('clientNameOverlay');
    const closeBtn = document.getElementById('clientNameClose');
    if (!btn || !overlay) return;

    function openOverlay() {
        overlay.classList.add('is-open');
        overlay.setAttribute('aria-hidden', 'false');
    }

    function closeOverlay() {
        overlay.classList.remove('is-open');
        overlay.setAttribute('aria-hidden', 'true');
    }

    btn.addEventListener('click', openOverlay);
    if (closeBtn) closeBtn.addEventListener('click', closeOverlay);
});
</script>
<?php endif; ?>

<?php if (($voznja['tip_usluge'] ?? 'transfer_od_do_adrese') === 'transfer_od_do_adrese' && !empty($voznja['polazna_adresa']) && !empty($voznja['dolazna_adresa'])): ?>
<script>
(function () {
    <?php
    if (!empty($voznja['polazna_lat']) && !empty($voznja['polazna_lng'])) {
        echo 'var routeOrigin = {lat: ' . floatval($voznja['polazna_lat']) . ', lng: ' . floatval($voznja['polazna_lng']) . '};';
    } else {
        echo 'var routeOrigin = ' . json_encode($voznja['polazna_adresa']) . ';';
    }
    if (!empty($voznja['dolazna_lat']) && !empty($voznja['dolazna_lng'])) {
        echo 'var routeDestination = {lat: ' . floatval($voznja['dolazna_lat']) . ', lng: ' . floatval($voznja['dolazna_lng']) . '};';
    } else {
        echo 'var routeDestination = ' . json_encode($voznja['dolazna_adresa']) . ';';
    }
    ?>

    function initRouteMap() {
        var mapEl = document.getElementById('route_map');
        if (!mapEl) return;

        var map = new google.maps.Map(mapEl, {
            zoom: 7,
            center: { lat: 44.787197, lng: 20.457273 },
            gestureHandling: 'cooperative',
            mapTypeControl: false,
            streetViewControl: false,
            fullscreenControl: true
        });

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

        directionsService.route({
            origin: routeOrigin,
            destination: routeDestination,
            travelMode: google.maps.TravelMode.DRIVING
        }, function (result, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                directionsRenderer.setDirections(result);
                var distanceMeters = 0;
                var legs = result.routes[0].legs;
                for (var i = 0; i < legs.length; i++) {
                    distanceMeters += legs[i].distance.value;
                }
                var badge = document.getElementById('route_distance_badge');
                if (badge) {
                    badge.textContent = (distanceMeters / 1000).toFixed(1) + ' km';
                    badge.style.display = '';
                }
            }
        });
    }

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

<a href="index.php" class="btn btn-warning btn-lg sticky-bottom-right">
    <i class="bi bi-arrow-left me-2"></i>Nazad
</a>

<style>
.sticky-bottom-right {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 1000;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 50px;
    padding: 12px 24px;
}

.sticky-bottom-left {
    position: fixed;
    bottom: 20px;
    left: 20px;
    z-index: 1000;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 50px;
    padding: 12px 24px;
}


.client-name-overlay {
    position: fixed;
    inset: 0;
    z-index: 2000;
    background: #000;
    color: #fff;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 7vh 2vw;
}

.client-name-overlay.is-open {
    display: flex;
}

.client-name-text {
    font-weight: 800;
    text-align: center;
    line-height: 1.05;
    font-size: min(15vw, 30vh);
    word-break: normal;
    overflow-wrap: break-word;
    max-width: 98vw;
    min-width: 0;
    box-sizing: border-box;
}

.client-name-close {
    position: fixed;
    top: 20px;
    right: 20px;
    border-radius: 999px;
    width: 64px;
    height: 64px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 40px;
    line-height: 1;
    z-index: 2001;
}

@media (max-width: 768px) {
    .sticky-bottom-right {
        bottom: 15px;
        right: 15px;
        padding: 10px 20px;
        font-size: 0.9rem;
    }
    .sticky-bottom-left {
        bottom: 15px;
        left: 15px;
        padding: 10px 20px;
        font-size: 0.9rem;
    }

    .client-name-close {
        top: 15px;
        right: 15px;
        width: 56px;
        height: 56px;
        font-size: 36px;
    }
}
</style>

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