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

if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    $stmt = $conn->prepare("SELECT komitent_id, datum, vreme, status FROM voznje WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        header("Location: index.php?error=Vožnja nije pronađena");
        exit;
    }
    
    $ride = $result->fetch_assoc();
    
    if (!isAdmin() && $ride['komitent_id'] != $_SESSION['user']['komitent_id']) {
        header("Location: index.php?error=Nemate pristup ovoj vožnji");
        exit;
    }
    
    if (!isAdmin()) {
        if ($ride['status'] !== 'Na čekanju') {
            header("Location: index.php?error=Možete obrisati samo vožnje koje su na čekanju");
            exit;
        }
        
        $stmt = $conn->prepare("UPDATE voznje SET status = 'Obrisano' WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            header("Location: index.php?success=Vožnja je uspešno obrisana");
        } else {
            header("Location: index.php?error=Greška prilikom brisanja vožnje");
        }
    } else {
        $stmt = $conn->prepare("DELETE FROM voznje WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            header("Location: index.php?success=Vožnja je uspešno obrisana");
        } else {
            header("Location: index.php?error=Greška prilikom brisanja vožnje");
        }
    }
} else {
    header("Location: index.php");
}
exit; 