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

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

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

// Provera da li vozač ima pristup ovoj vožnji
if (!isAdmin() && $_SESSION['user']['role'] === '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();
}

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

<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 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 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']) / 1.20, 2, ',', '.'); ?> RSD</p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted">Cena sa PDV-om (20%)</label>
                        <p class="mb-0"><strong><?php echo number_format(floatval($voznja['cena']), 2, ',', '.'); ?> RSD</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>

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

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

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