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

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'datum';
$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';

if (isset($_GET['month'])) {
    if ($_GET['month'] === 'all') {
        $selected_month = 'all';
    } elseif ($_GET['month'] !== '') {
        $selected_month = $_GET['month'];
    } else {
        $selected_month = date('Y-m');
    }
} else {
    $selected_month = date('Y-m');
}

$where_conditions = [];
$params = [];
$types = '';

if ($selected_month !== 'all' && $selected_month !== '') {
    $where_conditions[] = "DATE_FORMAT(v.datum, '%Y-%m') = ?";
    $params[] = $selected_month;
    $types .= 's';
}

if (!empty($search)) {
    $where_conditions[] = "(v.vrsta_vozila LIKE ? OR u.name LIKE ? OR v.ime_klijenta LIKE ? OR v.polazna_adresa LIKE ? OR v.dolazna_adresa LIKE ? OR v.broj_leta LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param, $search_param]);
    $types .= 'ssssss';
}

if (!isAdmin()) {
    if ($_SESSION['user']['role'] === 'vozac') {
        $where_conditions[] = "v.vozac_id = ?";
        $params[] = $_SESSION['user']['id'];
    } else {
        $where_conditions[] = "v.komitent_id = ?";
        $params[] = $_SESSION['user']['komitent_id'] ?? null;
        $where_conditions[] = "v.status != 'Obrisano'";
    }
    $types .= 'i';
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

$order_by_clause = "v.datum $order, v.vreme $order";
if ($sort === 'vrsta_vozila') {
    $order_by_clause = "v.vrsta_vozila $order, v.datum DESC, v.vreme DESC";
} elseif ($sort === 'vozac') {
    $order_by_clause = "u.name $order, v.datum DESC, v.vreme DESC";
} elseif ($sort === 'ime_klijenta') {
    $order_by_clause = "v.ime_klijenta $order, v.datum DESC, v.vreme DESC";
}

$items_per_page = getItemsPerPage();
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $items_per_page;

$params_for_count = $params;
$types_for_count = $types;

$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_clause 
        ORDER BY $order_by_clause
        LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $types .= 'ii';
    $params[] = $items_per_page;
    $params[] = $offset;
    $stmt->bind_param($types, ...$params);
} else {
    $stmt->bind_param("ii", $items_per_page, $offset);
}
$stmt->execute();
$result = $stmt->get_result();

$count_sql = "SELECT COUNT(*) as total FROM voznje v 
              LEFT JOIN komitenti k ON v.komitent_id = k.id 
              LEFT JOIN users u ON v.vozac_id = u.id 
              $where_clause";
$count_stmt = $conn->prepare($count_sql);
if (!empty($params_for_count)) {
    $count_stmt->bind_param($types_for_count, ...$params_for_count);
}
$count_stmt->execute();
$total_rows = (int)$count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = $total_rows > 0 ? max(1, ceil($total_rows / $items_per_page)) : 1;

if ($page > $total_pages && $total_pages > 0) {
    $page = $total_pages;
    $offset = ($page - 1) * $items_per_page;
}

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

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

<div class="container-fluid mt-4">
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php echo htmlspecialchars($_GET['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?php echo htmlspecialchars($_GET['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4">
        <h2 class="mb-0">Vožnje</h2>
        <div class="d-flex flex-wrap gap-2">
            <?php if (isAdmin() || (isset($_SESSION['user']['role']) && $_SESSION['user']['role'] === 'user' && isset($_SESSION['user']['komitent_id']))): ?>
                <a href="create.php" class="btn btn-primary"><i class="bi bi-plus-circle me-1"></i>Nova vožnja</a>
            <?php endif; ?>
            <a href="export.php<?php echo !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : ''; ?>" class="btn btn-success"><i class="bi bi-download me-1"></i>Export</a>
        </div>
    </div>

    <?php if (!isAdmin() && $_SESSION['user']['role'] === 'vozac'): ?>
        <!-- Card view for drivers -->
        <div class="row row-cols-1 row-cols-md-2 g-4">
            <?php while ($row = $result->fetch_assoc()): 
                $rideDate = strtotime($row['datum']);
                $today = strtotime('today');
                $status = '';
                $statusClass = '';
                
                if ($rideDate < $today) {
                    $status = 'Završeno';
                    $statusClass = 'status-past';
                } elseif ($rideDate == $today) {
                    $status = 'Danas';
                    $statusClass = 'status-today';
                } else {
                    $status = 'Predstojeće';
                    $statusClass = 'status-upcoming';
                }
            ?>
                <div class="col">
                    <div class="card ride-card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">
                                Vožnja #<?php echo htmlspecialchars($row['broj_leta'] ?? ''); ?>
                                <?php if (!empty($row['broj_leta'])): 
                                    $flightLinks = getFlightTrackingLinks($row['broj_leta']);
                                    if ($flightLinks): ?>
                                        <div class="dropdown d-inline ms-2">
                                            <button class="btn btn-sm btn-link p-0" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                <i class="bi bi-airplane text-primary"></i>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li><a class="dropdown-item" href="<?php echo htmlspecialchars($flightLinks['flightradar24']); ?>" target="_blank" rel="noopener noreferrer">
                                                    <i class="bi bi-globe me-2"></i>FlightRadar24
                                                </a></li>
                                                <li><a class="dropdown-item" href="<?php echo htmlspecialchars($flightLinks['flightstats']); ?>" target="_blank" rel="noopener noreferrer">
                                                    <i class="bi bi-globe me-2"></i>FlightStats
                                                </a></li>
                                            </ul>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </h5>
                            <span class="status-badge status-<?php echo statusToCssClass($row['status']); ?>">
                                <?php echo htmlspecialchars($row['status']); ?>
                            </span>
                        </div>
                        <div class="card-body">
                            <div class="ride-info">
                                <i class="bi bi-calendar-event"></i>
                                <strong>Datum:</strong> <?php echo date('d.m.Y', strtotime($row['datum'])); ?>
                            </div>
                            <div class="ride-info d-flex align-items-center gap-2">
                                <div>
                                    <i class="bi bi-clock"></i>
                                    <strong>Vreme:</strong> 
                                    <span data-bs-toggle="tooltip" 
                                          data-bs-placement="top" 
                                          data-bs-html="true"
                                          title="Kreirano: <?php echo !empty($row['created_at']) ? date('d.m.Y H:i', strtotime($row['created_at'])) : 'N/A'; ?><br>Ažurirano: <?php echo !empty($row['updated_at']) ? date('d.m.Y H:i', strtotime($row['updated_at'])) : 'N/A'; ?>"
                                          style="cursor: help; text-decoration: underline; text-decoration-style: dotted;">
                                        <?php echo date('H:i', strtotime($row['vreme'])); ?>
                                    </span>
                                </div>
                                <?php 
                                $tip_usluge = $row['tip_usluge'] ?? 'transfer_od_do_adrese';
                                $badge_text = $tip_usluge === 'na_sat' ? 'S' : 'T';
                                $badge_title = $tip_usluge === 'na_sat' ? 'Na sat' : 'Transfer od/do adrese';
                                if ($tip_usluge === 'na_sat' && !empty($row['broj_sati'])) {
                                    $badge_title .= ' (' . $row['broj_sati'] . 'h)';
                                }
                                ?>
                                <span class="badge bg-info" 
                                      data-bs-toggle="tooltip" 
                                      data-bs-placement="top" 
                                      title="<?php echo htmlspecialchars($badge_title); ?>"
                                      style="cursor: help;">
                                    <?php echo $badge_text; ?>
                                </span>
                            </div>
                            <div class="ride-info">
                                <i class="bi bi-truck"></i>
                                <strong>Vozilo:</strong> <?php echo htmlspecialchars($row['vrsta_vozila'] ?? ''); ?>
                            </div>
                            <div class="ride-info">
                                <i class="bi bi-person"></i>
                                <strong>Klijent:</strong> <?php echo htmlspecialchars($row['ime_klijenta'] ?? ''); ?>
                            </div>
                            <?php 
                            $tip_usluge_card = $row['tip_usluge'] ?? 'transfer_od_do_adrese';
                            if ($tip_usluge_card === 'transfer_od_do_adrese'): ?>
                            <div class="ride-info">
                                <i class="bi bi-geo-alt"></i>
                                <strong>Polazak:</strong> <?php echo htmlspecialchars($row['polazna_adresa'] ?? ''); ?>
                            </div>
                            <div class="ride-info">
                                <i class="bi bi-geo-alt-fill"></i>
                                <strong>Destinacija:</strong> <?php echo htmlspecialchars($row['dolazna_adresa'] ?? ''); ?>
                            </div>
                            <?php elseif ($tip_usluge_card === 'na_sat' && !empty($row['broj_sati'])): ?>
                            <div class="ride-info">
                                <i class="bi bi-clock-history"></i>
                                <strong>Trajanje:</strong> <?php echo $row['broj_sati']; ?> sati
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="card-footer bg-transparent">
                            <div class="btn-group w-100">
                                <a href="pregled.php?id=<?php echo $row['id']; ?>" class="btn btn-primary"><i class="bi bi-eye me-1"></i>Pregled</a>
                                <?php if ($row['status'] === 'Predstoji'): ?>
                                    <a href="zavrsi.php?id=<?php echo $row['id']; ?>" class="btn btn-success" 
                                       onclick="return confirm('Da li ste sigurni da želite da označite ovu vožnju kao završenu?')"><i class="bi bi-check-circle me-1"></i>Završi</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    <?php else: ?>
        <!-- Table view for admins and regular users -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-3">
                        <label for="month" class="form-label">Mesec</label>
                        <select class="form-select" id="month" name="month">
                            <option value="all" <?php echo $selected_month === 'all' ? 'selected' : ''; ?>>Svi meseci</option>
                            <?php
                            $current_date = new DateTime();
                            $months = [];
                            
                            for ($i = -3; $i <= 3; $i++) {
                                $date = clone $current_date;
                                $date->modify("$i months");
                                $months[] = [
                                    'value' => $date->format('Y-m'),
                                    'label' => $date->format('F Y'),
                                    'serbian' => $date->format('m.Y')
                                ];
                            }
                            
                            $serbian_months = [
                                'January' => 'Januar', 'February' => 'Februar', 'March' => 'Mart',
                                'April' => 'April', 'May' => 'Maj', 'June' => 'Jun',
                                'July' => 'Jul', 'August' => 'Avgust', 'September' => 'Septembar',
                                'October' => 'Oktobar', 'November' => 'Novembar', 'December' => 'Decembar'
                            ];
                            
                            foreach ($months as $month) {
                                $month_name = date('F', strtotime($month['value'] . '-01'));
                                $serbian_name = $serbian_months[$month_name] ?? $month_name;
                                $display = $serbian_name . ' ' . date('Y', strtotime($month['value'] . '-01'));
                                $is_selected = ($selected_month === $month['value']) ? 'selected' : '';
                                echo "<option value=\"{$month['value']}\" {$is_selected}>{$display}</option>";
                            }
                            ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="search" class="form-label">Pretraži</label>
                        <input type="text" class="form-control" id="search" name="search" placeholder="Pretraži..." value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-2">
                        <label for="sort" class="form-label">Sortiraj po</label>
                        <select class="form-select" id="sort" name="sort">
                            <option value="datum" <?php echo $sort === 'datum' ? 'selected' : ''; ?>>Datum</option>
                            <option value="vrsta_vozila" <?php echo $sort === 'vrsta_vozila' ? 'selected' : ''; ?>>Vozilo</option>
                            <option value="vozac" <?php echo $sort === 'vozac' ? 'selected' : ''; ?>>Vozač</option>
                            <option value="ime_klijenta" <?php echo $sort === 'ime_klijenta' ? 'selected' : ''; ?>>Klijent</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="order" class="form-label">Redosled</label>
                        <select class="form-select" id="order" name="order">
                            <option value="DESC" <?php echo $order === 'DESC' ? 'selected' : ''; ?>>Opadajuće</option>
                            <option value="ASC" <?php echo $order === 'ASC' ? 'selected' : ''; ?>>Rastuće</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <div>
                            <button type="submit" class="btn btn-dark w-100"><i class="bi bi-funnel me-1"></i>Filtriraj</button>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <?php if (!empty($search) || $sort !== 'datum' || $order !== 'DESC' || ($selected_month !== date('Y-m') && $selected_month !== 'all')): ?>
                            <a href="index.php" class="btn btn-secondary"><i class="bi bi-arrow-counterclockwise me-1"></i>Resetuj</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th width="50" class="text-center"></th>
                        <?php if (isAdmin()): ?>
                        <th width="50" class="text-center">Vozač</th>
                        <?php endif; ?>
                        <th>Datum i vreme</th>
                        <th>Broj leta</th>
                        <th>Polazna adresa</th>
                        <th>Dolazna adresa</th>
                        <th>Ime klijenta</th>
                        <?php if (isAdmin()): ?>
                        <th>Naručilac</th>
                        <?php endif; ?>
                        <th>Vrsta vozila</th>
                        <th>Status</th>
                        <th class="text-center" width="80">Akcije</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result->num_rows === 0): ?>
                        <tr>
                            <td colspan="<?php echo isAdmin() ? '12' : '10'; ?>" class="text-center">Nema vožnji</td>
                        </tr>
                    <?php else: ?>
                        <?php while ($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td class="text-center">
                                    <?php if (isAdmin()): ?>
                                        <div class="position-relative d-inline-block">
                                            <a href="pregled.php?id=<?php echo $row['id']; ?>" class="btn btn-dark">
                                                <i class="bi bi-eye"></i>
                                            </a>
                                            <?php if (!empty($row['attachment'])): ?>
                                                <a href="<?php echo htmlspecialchars($row['attachment']); ?>" target="_blank" class="badge bg-danger position-absolute top-0 start-100 translate-middle rounded-circle" title="Prilog" style="text-decoration: none; padding: 0.25em 0.4em; font-size: 0.7em;">
                                                    <i class="bi bi-paperclip"></i>
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    <?php elseif (!empty($row['attachment'])): ?>
                                        <a href="<?php echo htmlspecialchars($row['attachment']); ?>" target="_blank" class="btn btn-sm btn-outline-info" title="Prilog">
                                            <i class="bi bi-paperclip"></i>
                                        </a>
                                    <?php endif; ?>
                                </td>
                                <?php if (isAdmin()): ?>
                                <td class="text-center">
                                    <?php 
                                    $hasDriver = !empty($row['vozac_id']);
                                    $btnClass = $hasDriver ? 'btn-primary' : 'btn-outline-secondary';
                                    $icon = $hasDriver ? 'bi-person-check-fill' : 'bi-person-plus';
                                    $tooltip = $hasDriver ? htmlspecialchars($row['vozac_ime']) : 'Dodeli vozača';
                                    
                                    
                                    if (!empty($row['vozac_telefon'])) {
                                        $tooltip.= "\n" . htmlspecialchars($row['vozac_telefon']);
                                    }
                                    
                                    
                                    ?>
                                    <button class="btn <?php echo $btnClass; ?> btn-assign-driver" 
                                            data-voznja-id="<?php echo $row['id']; ?>"
                                            data-vozac-id="<?php echo $row['vozac_id'] ?? ''; ?>"
                                            data-bs-toggle="tooltip"
                                            data-bs-placement="top"
                                            title="<?php echo $tooltip; ?>">
                                        <i class="bi <?php echo $icon; ?>"></i>
                                    </button>
                                </td>
                                <?php endif; ?>
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <div>
                                            <div><?php echo date('d.m.Y', strtotime($row['datum'])); ?></div>
                                            <small class="text-muted" 
                                                   data-bs-toggle="tooltip" 
                                                   data-bs-placement="top" 
                                                   data-bs-html="true"
                                                   title="Kreirano: <?php echo !empty($row['created_at']) ? date('d.m.Y H:i', strtotime($row['created_at'])) : 'N/A'; ?><br>Ažurirano: <?php echo !empty($row['updated_at']) ? date('d.m.Y H:i', strtotime($row['updated_at'])) : 'N/A'; ?>"
                                                   style="cursor: help; text-decoration: underline; text-decoration-style: dotted;">
                                                <?php echo date('H:i', strtotime($row['vreme'])); ?>
                                            </small>
                                            <?php 
                                        $tip_usluge = $row['tip_usluge'] ?? 'transfer_od_do_adrese';
                                        $badge_text = $tip_usluge === 'na_sat' ? 'S' : 'T';
                                        $badge_title = $tip_usluge === 'na_sat' ? 'Na sat' : 'Transfer od/do adrese';
                                        if ($tip_usluge === 'na_sat' && !empty($row['broj_sati'])) {
                                            $badge_title .= ' (' . $row['broj_sati'] . 'h)';
                                            $badge_class = 'bg-danger';
                                        } else {
                                            $badge_class = 'bg-dark';
                                        }
                                        ?>
                                        <span class="badge rounded-pill <?php echo $badge_class; ?> text-small" 
                                              data-bs-toggle="tooltip" 
                                              data-bs-placement="top" 
                                              title="<?php echo htmlspecialchars($badge_title); ?>"
                                              style="cursor: help; font-size: 0.5rem; vertical-align: middle;">
                                            <?php echo $badge_text; ?>
                                        </span>
                                        </div>

                                    </div>
                                </td>
                                <td>
                                    <?php 
                                    if (!empty($row['broj_leta'])) {
                                        $flightLinks = getFlightTrackingLinks($row['broj_leta']);
                                        if ($flightLinks) { ?>
                                            <div class="dropdown d-inline">
                                                <span class="d-inline-flex align-items-center">
                                                    <?php echo htmlspecialchars($row['broj_leta']); ?>
                                                    <button class="btn btn-sm btn-link p-0 ms-1" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                        <i class="bi bi-airplane text-primary"></i>
                                                    </button>
                                                </span>
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="<?php echo htmlspecialchars($flightLinks['flightradar24']); ?>" target="_blank" rel="noopener noreferrer">
                                                        <i class="bi bi-globe me-2"></i>FlightRadar24
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="<?php echo htmlspecialchars($flightLinks['flightstats']); ?>" target="_blank" rel="noopener noreferrer">
                                                        <i class="bi bi-globe me-2"></i>FlightStats
                                                    </a></li>
                                                </ul>
                                            </div>
                                        <?php } else { ?>
                                            <?php echo htmlspecialchars($row['broj_leta']); ?>
                                        <?php }
                                    } else { ?>
                                        -
                                    <?php } ?>
                                </td>
                                <td>
                                    <?php 
                                    $tip_usluge_table = $row['tip_usluge'] ?? 'transfer_od_do_adrese';
                                    if ($tip_usluge_table === 'transfer_od_do_adrese'): 
                                        echo htmlspecialchars($row['polazna_adresa'] ?? '');
                                    else: 
                                        echo '<span class="text-muted">-</span>';
                                    endif; 
                                    ?>
                                </td>
                                <td>
                                    <?php 
                                    if ($tip_usluge_table === 'transfer_od_do_adrese'): 
                                        echo htmlspecialchars($row['dolazna_adresa'] ?? '');
                                    else: 
                                        echo '<span class="text-muted">-</span>';
                                    endif; 
                                    ?>
                                </td>
                                <td><?php echo htmlspecialchars($row['ime_klijenta'] ?? ''); ?></td>
                                <?php if (isAdmin()): ?>
                                <td><?php echo htmlspecialchars($row['komitent_naziv'] ?? ''); ?></td>
                                <?php endif; ?>
                                <td><?php echo htmlspecialchars($row['vrsta_vozila'] ?? ''); ?></td>
                                <td>
                                    <?php if (isAdmin()): ?>
                                        <select class="form-select status-select status-<?php echo statusToCssClass($row['status']); ?>" 
                                                onchange="updateStatus(<?php echo $row['id']; ?>, this.value)">
                                            <option value="Na čekanju" <?php echo $row['status'] === 'Na čekanju' ? 'selected' : ''; ?>>Na čekanju</option>
                                            <option value="Nerasporedjeno" <?php echo $row['status'] === 'Nerasporedjeno' ? 'selected' : ''; ?>>Nerasporedjeno</option>
                                            <option value="Predstoji" <?php echo $row['status'] === 'Predstoji' ? 'selected' : ''; ?>>Predstoji</option>
                                            <option value="Završeno" <?php echo $row['status'] === 'Završeno' ? 'selected' : ''; ?>>Završeno</option>
                                            <option value="Arhivirano" <?php echo $row['status'] === 'Arhivirano' ? 'selected' : ''; ?>>Arhivirano</option>
                                            <option value="Odbijeno" <?php echo $row['status'] === 'Odbijeno' ? 'selected' : ''; ?>>Odbijeno</option>
                                        </select>
                                    <?php else: ?>
                                        <span class="status-badge status-<?php echo statusToCssClass($row['status']); ?>">
                                            <?php echo htmlspecialchars($row['status']); ?>
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <div class="btn-group">
                                        <?php if (isAdmin() || $row['status'] === 'Na čekanju' || $row['status'] === 'Nerasporedjeno' || $row['status'] === 'Predstoji'): ?>
                                            <a href="edit.php?id=<?php echo $row['id']; ?>" class="btn btn-dark" title="Izmeni" data-bs-toggle="tooltip">
                                                <?php if (isAdmin()): ?>
                                                    <i class="bi bi-pencil-square"></i>
                                                <?php else: ?>
                                                    <i class="bi bi-pencil-square me-1"></i>Izmeni
                                                <?php endif; ?>
                                            </a>
                                        <?php endif; ?>
                                        <?php if (isAdmin() || ($row['status'] === 'Na čekanju' && $_SESSION['user']['role'] !== 'admin')): ?>
                                            <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger" onclick="return confirm('Da li ste sigurni da želite da obrišete ovu vožnju?')" title="Obriši" data-bs-toggle="tooltip">
                                                <?php if (isAdmin()): ?>
                                                    <i class="bi bi-trash"></i>
                                                <?php else: ?>
                                                    <i class="bi bi-trash me-1"></i>Obriši
                                                <?php endif; ?>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total_pages > 1): ?>
            <nav aria-label="Paginacija">
                <ul class="pagination justify-content-center mt-4">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo htmlspecialchars(http_build_query(array_merge($_GET, ['page' => max(1, $page - 1)]))); ?>">Prethodna</a>
                    </li>
                    <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?<?php echo htmlspecialchars(http_build_query(array_merge($_GET, ['page' => $i]))); ?>"><?php echo htmlspecialchars((string)$i); ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo htmlspecialchars(http_build_query(array_merge($_GET, ['page' => min($total_pages, $page + 1)]))); ?>">Sledeća</a>
                    </li>
                </ul>
            </nav>
            <div class="text-center text-muted mb-4">
                <?php if ($total_rows > 0): ?>
                    Prikazano <?php echo min($offset + 1, $total_rows); ?>-<?php echo min($offset + $items_per_page, $total_rows); ?> od <?php echo $total_rows; ?> vožnji
                <?php else: ?>
                    Nema vožnji za prikaz
                <?php endif; ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Modal za dodelu vozača -->
<div class="modal fade" id="assignDriverModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Dodeli vozača</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="assignDriverForm">
                    <input type="hidden" id="assign_voznja_id" name="voznja_id">
                    <div class="mb-3">
                        <label for="assign_vozac_id" class="form-label">Izaberi vozača</label>
                        <select class="form-select" id="assign_vozac_id" name="vozac_id" required>
                            <option value="">Bez vozača</option>
                            <?php
                            $vozaci_stmt = $conn->prepare("SELECT id, name, telefon FROM users WHERE role = 'vozac' AND active = 1 ORDER BY name");
                            $vozaci_stmt->execute();
                            $vozaci_result = $vozaci_stmt->get_result();
                            while ($vozac = $vozaci_result->fetch_assoc()):
                            ?>
                                <option value="<?php echo $vozac['id']; ?>"><?php echo htmlspecialchars($vozac['name']); ?><?php echo !empty($vozac['telefon']) ? ' (' . htmlspecialchars($vozac['telefon']) . ')' : ''; ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="email_napomena" class="form-label">Napomena za email (opciono)</label>
                        <textarea class="form-control" id="email_napomena" name="email_napomena" rows="3" placeholder="Ova napomena će biti uključena u email koji će vozač primiti..."></textarea>
                        <div class="form-text">Ova napomena se ne čuva u bazi, samo se šalje u email notifikaciji.</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="confirmAssignDriver">Dodeli vozača</button>
            </div>
        </div>
    </div>
</div>

<?php if (isCompactView()): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.body.classList.add('compact-view');
});
</script>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        var options = {};
        if (tooltipTriggerEl.getAttribute('data-bs-html') === 'true') {
            options.html = true;
        }
        return new bootstrap.Tooltip(tooltipTriggerEl, options);
    });
    
    var monthSelect = document.getElementById('month');
    if (monthSelect) {
        monthSelect.addEventListener('change', function() {
            this.form.submit();
        });
    }
    
    // Dodela vozača modal
    var assignDriverModal = document.getElementById('assignDriverModal');
    if (assignDriverModal) {
        var modal = new bootstrap.Modal(assignDriverModal);
        var assignButtons = document.querySelectorAll('.btn-assign-driver');
        
        assignButtons.forEach(function(btn) {
            btn.addEventListener('click', function() {
                var voznjaId = this.getAttribute('data-voznja-id');
                var vozacId = this.getAttribute('data-vozac-id');
                
                document.getElementById('assign_voznja_id').value = voznjaId;
                document.getElementById('assign_vozac_id').value = vozacId;
                document.getElementById('email_napomena').value = '';
                
                modal.show();
            });
        });
        
        document.getElementById('confirmAssignDriver').addEventListener('click', function() {
            var vozacId = document.getElementById('assign_vozac_id').value;
            var vozacName = document.getElementById('assign_vozac_id').options[document.getElementById('assign_vozac_id').selectedIndex].text;
            
            var confirmMessage = vozacId 
                ? 'Da li ste sigurni da želite da dodelite vozača "' + vozacName + '" ovoj vožnji?' 
                : 'Da li ste sigurni da želite da uklonite dodeljenog vozača sa ove vožnje?';
            
            if (confirm(confirmMessage)) {
                var formData = new FormData(document.getElementById('assignDriverForm'));
                
                fetch('assign_driver.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        modal.hide();
                        location.reload();
                    } else {
                        alert('Greška: ' + (data.message || 'Nepoznata greška'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Greška prilikom komunikacije sa serverom');
                });
            }
        });
    }
});

function updateStatus(id, status) {
    const select = event.target;
    const originalStatus = select.value;
    
    fetch('update_status.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `id=${id}&status=${status}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const statusClass = status.toLowerCase().replace(/[čćšžđ]/g, function(match) {
                const map = {'č': 'c', 'ć': 'c', 'š': 's', 'ž': 'z', 'đ': 'd'};
                return map[match] || match;
            }).replace(/\s+/g, '-');
            select.className = `form-select status-select status-${statusClass}`;
        } else {
            alert(data.message || 'Greška prilikom ažuriranja statusa');
            select.value = originalStatus;
            const originalStatusClass = originalStatus.toLowerCase().replace(/[čćšžđ]/g, function(match) {
                const map = {'č': 'c', 'ć': 'c', 'š': 's', 'ž': 'z', 'đ': 'd'};
                return map[match] || match;
            }).replace(/\s+/g, '-');
            select.className = `form-select status-select status-${originalStatusClass}`;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Greška prilikom komunikacije sa serverom');
        select.value = originalStatus;
        const originalStatusClass = originalStatus.toLowerCase().replace(/[čćšžđ]/g, function(match) {
            const map = {'č': 'c', 'ć': 'c', 'š': 's', 'ž': 'z', 'đ': 'd'};
            return map[match] || match;
        }).replace(/\s+/g, '-');
        select.className = `form-select status-select status-${originalStatusClass}`;
    });
}
</script>

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