<?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()) {
    if (($_SESSION['user']['role'] ?? null) !== 'vozac') {
        header("Location: index.php");
        exit();
    }

    $stmt = $conn->prepare("SELECT id, status FROM voznje WHERE id = ? AND vozac_id = ?");
    $stmt->bind_param("ii", $id, $_SESSION['user']['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    $voznja_check = $result->fetch_assoc();
    if (!$voznja_check) {
        header("Location: index.php");
        exit();
    }
    if ($voznja_check['status'] !== 'Predstoji') {
        header("Location: index.php?error=" . urlencode("Možete završiti samo vožnje sa statusom 'Predstoji'."));
        exit();
    }
}

// Učitavanje informacija o vožnji
$sql = "SELECT v.*, k.naziv as komitent_naziv, u.name as vozac_ime 
        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();
}

$uploaded_documents = [];
$stmt_docs = $conn->prepare("SELECT * FROM dokumenti WHERE voznja_id = ? AND tip = 'zavrsenje_voznje' ORDER BY vreme DESC");
$stmt_docs->bind_param("i", $id);
$stmt_docs->execute();
$result_docs = $stmt_docs->get_result();
while ($doc = $result_docs->fetch_assoc()) {
    $uploaded_documents[] = $doc;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $dodatni_troskovi = trim($_POST['dodatni_troskovi'] ?? '');
    $napomena_voznja = trim($_POST['napomena_voznja'] ?? '');
    
    $uploadDir = __DIR__ . '/uploads/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    $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'];
    
    $maxFileSize = 10 * 1024 * 1024;
    $uploadedFiles = [];
    $uploadErrors = [];
    
    if (isset($_FILES['dokumenti'])) {
        $files = $_FILES['dokumenti'];
        
        if (is_array($files['name'])) {
            $fileCount = count($files['name']);
        } else {
            $fileCount = 1;
            $files = [
                'name' => [$files['name']],
                'type' => [$files['type']],
                'tmp_name' => [$files['tmp_name']],
                'error' => [$files['error']],
                'size' => [$files['size']]
            ];
        }
        
        if ($fileCount > 5) {
            $uploadErrors[] = "Maksimalno 5 fajlova je dozvoljeno.";
        } else {
            for ($i = 0; $i < $fileCount; $i++) {
                if (!isset($files['error'][$i]) || $files['error'][$i] === UPLOAD_ERR_NO_FILE) {
                    continue;
                }
                
                if ($files['error'][$i] !== UPLOAD_ERR_OK) {
                    $uploadErrors[] = "Greška pri upload-u fajla (error code: " . $files['error'][$i] . ").";
                    continue;
                }
                
                $fileName = $files['name'][$i];
                $fileTmpName = $files['tmp_name'][$i];
                $fileSize = $files['size'][$i];
                $fileType = $files['type'][$i];
                
                if (!is_uploaded_file($fileTmpName)) {
                    $uploadErrors[] = "Fajl '{$fileName}' nije validan upload.";
                    continue;
                }
                
                if ($fileSize > $maxFileSize) {
                    $uploadErrors[] = "Fajl '{$fileName}' je prevelik (maksimalno 10MB).";
                    continue;
                }
                
                if (!in_array($fileType, $allowedTypes)) {
                    $uploadErrors[] = "Fajl '{$fileName}' nije dozvoljenog formata.";
                    continue;
                }
                
                $uniqueFileName = time() . '_' . uniqid() . '_' . basename($fileName);
                $targetPath = $uploadDir . $uniqueFileName;
                
                if (move_uploaded_file($fileTmpName, $targetPath)) {
                    $relativePath = 'uploads/' . $uniqueFileName;
                    
                    $stmt_ins = $conn->prepare("INSERT INTO dokumenti (uploaded_by, voznja_id, tip, naziv_fajla, putanja, velicina_fajla, mime_type) VALUES (?, ?, 'zavrsenje_voznje', ?, ?, ?, ?)");
                    $stmt_ins->bind_param("iissis", $_SESSION['user']['id'], $id, $fileName, $relativePath, $fileSize, $fileType);
                    
                    if ($stmt_ins->execute()) {
                        $uploadedFiles[] = $fileName;
                    } else {
                        unlink($targetPath);
                        $uploadErrors[] = "Greška pri čuvanju '{$fileName}' u bazu: " . $stmt_ins->error;
                    }
                    $stmt_ins->close();
                } else {
                    $uploadErrors[] = "Greška pri upload-u fajla '{$fileName}'.";
                }
            }
        }
    }
    
    if (!empty($uploadErrors)) {
        $error = implode(" ", $uploadErrors);
    }
    
    $stmt = $conn->prepare("UPDATE voznje SET status = 'Završeno', troskovi = ?, komentar = ? WHERE id = ?");
    $stmt->bind_param("ssi", $dodatni_troskovi, $napomena_voznja, $id);
    
    if ($stmt->execute()) {
        if (!empty($uploadedFiles)) {
            header("Location: index.php?success=" . urlencode("Vožnja završena. Uploadovano fajlova: " . count($uploadedFiles)));
        } else {
            header("Location: index.php?success=Vožnja je uspešno završena.");
        }
        exit();
    } else {
        $error = $error ?? "Greška prilikom završetka vožnje.";
    }
}

include "header.php";
?>

<div class="container-fluid mt-4">
    <div class="row justify-content-center">
        <div class="col-lg-10 col-xl-8">
            <div class="card">
                <div class="card-header">
                    <h3 class="mb-0">Završetak vožnje #<?php echo htmlspecialchars($voznja['broj_leta'] ?? ''); ?></h3>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <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">Klijent</label>
                                <p class="mb-0"><?php echo htmlspecialchars($voznja['ime_klijenta'] ?? ''); ?></p>
                            </div>
                        </div>
                        <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 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>

                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                    <?php endif; ?>

                    <?php if (!empty($uploaded_documents)): ?>
                    <div class="mb-4">
                        <label class="form-label fw-bold">Uploadovani dokumenti</label>
                        <div class="list-group">
                            <?php foreach ($uploaded_documents as $doc): ?>
                            <div class="list-group-item 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">
                                        <?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>
                                <small class="text-muted">
                                    <?php echo date('d.m.Y H:i', strtotime($doc['vreme'])); ?>
                                </small>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <form method="POST" action="" enctype="multipart/form-data">
                        <div class="mb-4">
                            <label for="dodatni_troskovi" class="form-label">
                                Napomena o dodatnim troškovima
                            </label>
                            <textarea 
                                class="form-control" 
                                id="dodatni_troskovi" 
                                name="dodatni_troskovi" 
                                rows="10"
                                style="height: 35vh; resize: vertical;"
                                placeholder="Unesite napomenu o dodatnim troškovima..."><?php echo htmlspecialchars($voznja['troskovi'] ?? ''); ?></textarea>
                        </div>

                        <div class="mb-4">
                            <label for="napomena_voznja" class="form-label">
                                Napomena o vožnji i putnicima
                            </label>
                            <textarea 
                                class="form-control" 
                                id="napomena_voznja" 
                                name="napomena_voznja" 
                                rows="10"
                                style="height: 35vh; resize: vertical;"
                                placeholder="Unesite napomenu o vožnji i putnicima..."><?php echo htmlspecialchars($voznja['komentar'] ?? ''); ?></textarea>
                        </div>

                        <div class="mb-4">
                            <label for="dokumenti" class="form-label">
                                Dokumenti (maksimalno 5 fajlova)
                            </label>
                            <input 
                                type="file" 
                                class="form-control" 
                                id="dokumenti" 
                                name="dokumenti[]" 
                                multiple 
                                accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif"
                                onchange="validateFiles(this)">
                            <div class="form-text">
                                Dozvoljeni formati: PDF, Word, Excel, slike. Maksimalna veličina po fajlu: 10MB.
                            </div>
                            <div id="file-list" class="mt-2"></div>
                        </div>

                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-success btn-lg py-3">
                                <i class="bi bi-check-circle me-2"></i>
                                Završi vožnju
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                Otkaži
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function validateFiles(input) {
    const fileList = document.getElementById('file-list');
    fileList.innerHTML = '';
    
    if (input.files.length > 5) {
        fileList.innerHTML = '<div class="alert alert-danger">Maksimalno 5 fajlova je dozvoljeno. Odabrano: ' + input.files.length + '</div>';
        input.value = '';
        return;
    }
    
    const maxSize = 10 * 1024 * 1024;
    const 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'];
    
    let hasErrors = false;
    let fileListHTML = '<div class="list-group mt-2">';
    
    for (let i = 0; i < input.files.length; i++) {
        const file = input.files[i];
        let isValid = true;
        let errorMsg = '';
        
        if (file.size > maxSize) {
            isValid = false;
            errorMsg = 'Prevelik fajl (maks 10MB)';
            hasErrors = true;
        }
        
        if (!allowedTypes.includes(file.type)) {
            isValid = false;
            errorMsg = 'Nedozvoljen format';
            hasErrors = true;
        }
        
        fileListHTML += '<div class="list-group-item ' + (isValid ? '' : 'list-group-item-danger') + '">';
        fileListHTML += '<div class="d-flex justify-content-between align-items-center">';
        fileListHTML += '<span><i class="bi bi-file-earmark me-2"></i>' + file.name + '</span>';
        fileListHTML += '<span class="badge bg-secondary">' + (file.size / 1024).toFixed(2) + ' KB</span>';
        if (!isValid) {
            fileListHTML += '<span class="badge bg-danger ms-2">' + errorMsg + '</span>';
        }
        fileListHTML += '</div></div>';
    }
    
    fileListHTML += '</div>';
    
    if (hasErrors) {
        fileList.innerHTML = '<div class="alert alert-warning">Neki fajlovi nisu validni. Molimo proverite i pokušajte ponovo.</div>' + fileListHTML;
    } else if (input.files.length > 0) {
        fileList.innerHTML = fileListHTML;
    }
}
</script>

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