<?php
require_once "config.php";
require_once "auth.php";

requireAdmin();

$message = '';
$error = '';

$isEdit = isset($_GET['id']);
$rental_id = $isEdit ? (int)$_GET['id'] : 0;

$rental = null;
$existingFiles = [];

if ($isEdit) {
    $stmt = $conn->prepare("SELECT * FROM rent_a_car WHERE id = ?");
    $stmt->bind_param("i", $rental_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $rental = $result->fetch_assoc();
    
    if (!$rental) {
        header('Location: rent_a_car.php');
        exit;
    }
    
    $stmt = $conn->prepare("SELECT * FROM rent_a_car_dokumenti WHERE rent_a_car_id = ? ORDER BY created_at");
    $stmt->bind_param("i", $rental_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $existingFiles = $result->fetch_all(MYSQLI_ASSOC);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $korisnik_id = $_SESSION['user']['id'];
    $korisnik_najma = trim($_POST['korisnik_najma'] ?? '');
    $adresa = trim($_POST['adresa'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $telefon = trim($_POST['telefon'] ?? '');
    $vozio_preuzeo = trim($_POST['vozio_preuzeo'] ?? '');
    $broj_licne_pasos = trim($_POST['broj_licne_pasos'] ?? '');
    $broj_vozacke = trim($_POST['broj_vozacke'] ?? '');
    $drugi_vozac = trim($_POST['drugi_vozac'] ?? '');
    $drugi_vozac_broj_licne = trim($_POST['drugi_vozac_broj_licne'] ?? '');
    $drugi_vozac_broj_vozacke = trim($_POST['drugi_vozac_broj_vozacke'] ?? '');
    $tip_marka_vozila = trim($_POST['tip_marka_vozila'] ?? '');
    $registarska_oznaka = trim($_POST['registarska_oznaka'] ?? '');
    $pocetak_mesto = trim($_POST['pocetak_mesto'] ?? '');
    $pocetak_datum = !empty($_POST['pocetak_datum']) ? $_POST['pocetak_datum'] : null;
    $pocetak_vreme = !empty($_POST['pocetak_vreme']) ? $_POST['pocetak_vreme'] : null;
    $zavrsetak_mesto = trim($_POST['zavrsetak_mesto'] ?? '');
    $zavrsetak_datum = !empty($_POST['zavrsetak_datum']) ? $_POST['zavrsetak_datum'] : null;
    $zavrsetak_vreme = !empty($_POST['zavrsetak_vreme']) ? $_POST['zavrsetak_vreme'] : null;
    $produzetak_najma = isset($_POST['produzetak_najma']) ? trim($_POST['produzetak_najma']) : 'ne';
    $produzetak_najma = ($produzetak_najma === 'da') ? 'da' : 'ne';
    
    if ($produzetak_najma !== 'da' && $produzetak_najma !== 'ne') {
        $produzetak_najma = 'ne';
    }
    $broj_produzenih_dana = !empty($_POST['broj_produzenih_dana']) ? (int)$_POST['broj_produzenih_dana'] : 0;
    $pocetna_kilometraza = !empty($_POST['pocetna_kilometraza']) ? (float)$_POST['pocetna_kilometraza'] : null;
    $zavrsena_kilometraza = !empty($_POST['zavrsena_kilometraza']) ? (float)$_POST['zavrsena_kilometraza'] : null;
    $predjena_kilometraza = null;
    $ukupan_period_najma = null;
    $iznos_depozita = !empty($_POST['iznos_depozita']) ? (float)$_POST['iznos_depozita'] : 0;
    $ukupno_za_naplati = !empty($_POST['ukupno_za_naplati']) ? (float)$_POST['ukupno_za_naplati'] : 0;
    
    if ($pocetna_kilometraza !== null && $zavrsena_kilometraza !== null) {
        $predjena_kilometraza = $zavrsena_kilometraza - $pocetna_kilometraza;
    }
    
    if ($pocetak_datum && $zavrsetak_datum) {
        $date1 = new DateTime($pocetak_datum);
        $date2 = new DateTime($zavrsetak_datum);
        $diff = $date1->diff($date2);
        $ukupan_period_najma = $diff->days + $broj_produzenih_dana;
    } elseif ($broj_produzenih_dana > 0) {
        $ukupan_period_najma = $broj_produzenih_dana;
    }
    
    if (empty($korisnik_najma) || empty($adresa) || empty($vozio_preuzeo) || empty($broj_licne_pasos) || empty($broj_vozacke)) {
        $error = "Korisnik najma, adresa, vozio preuzeo, broj lične karte/pasoša i broj vozačke dozvole su obavezna polja.";
    } else {
        if ($produzetak_najma !== 'da' && $produzetak_najma !== 'ne') {
            $produzetak_najma = 'ne';
        }
        
        if ($isEdit) {
            $sql = "UPDATE rent_a_car SET korisnik_najma = ?, adresa = ?, email = ?, telefon = ?, vozio_preuzeo = ?, broj_licne_pasos = ?, broj_vozacke = ?, drugi_vozac = ?, drugi_vozac_broj_licne = ?, drugi_vozac_broj_vozacke = ?, tip_marka_vozila = ?, registarska_oznaka = ?, pocetak_mesto = ?, pocetak_datum = ?, pocetak_vreme = ?, zavrsetak_mesto = ?, zavrsetak_datum = ?, zavrsetak_vreme = ?, produzetak_najma = '$produzetak_najma', broj_produzenih_dana = ?, pocetna_kilometraza = ?, zavrsena_kilometraza = ?, predjena_kilometraza = ?, ukupan_period_najma = ?, iznos_depozita = ?, ukupno_za_naplati = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssssssssssssssiidddiddi", $korisnik_najma, $adresa, $email, $telefon, $vozio_preuzeo, $broj_licne_pasos, $broj_vozacke, $drugi_vozac, $drugi_vozac_broj_licne, $drugi_vozac_broj_vozacke, $tip_marka_vozila, $registarska_oznaka, $pocetak_mesto, $pocetak_datum, $pocetak_vreme, $zavrsetak_mesto, $zavrsetak_datum, $zavrsetak_vreme, $broj_produzenih_dana, $pocetna_kilometraza, $zavrsena_kilometraza, $predjena_kilometraza, $ukupan_period_najma, $iznos_depozita, $ukupno_za_naplati, $rental_id);
        } else {
            $sql = "INSERT INTO rent_a_car (korisnik_id, korisnik_najma, adresa, email, telefon, vozio_preuzeo, broj_licne_pasos, broj_vozacke, drugi_vozac, drugi_vozac_broj_licne, drugi_vozac_broj_vozacke, tip_marka_vozila, registarska_oznaka, pocetak_mesto, pocetak_datum, pocetak_vreme, zavrsetak_mesto, zavrsetak_datum, zavrsetak_vreme, produzetak_najma, broj_produzenih_dana, pocetna_kilometraza, zavrsena_kilometraza, predjena_kilometraza, ukupan_period_najma, iznos_depozita, ukupno_za_naplati) VALUES ($korisnik_id, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '$produzetak_najma', ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssssssssssssssiidddidd", $korisnik_najma, $adresa, $email, $telefon, $vozio_preuzeo, $broj_licne_pasos, $broj_vozacke, $drugi_vozac, $drugi_vozac_broj_licne, $drugi_vozac_broj_vozacke, $tip_marka_vozila, $registarska_oznaka, $pocetak_mesto, $pocetak_datum, $pocetak_vreme, $zavrsetak_mesto, $zavrsetak_datum, $zavrsetak_vreme, $broj_produzenih_dana, $pocetna_kilometraza, $zavrsena_kilometraza, $predjena_kilometraza, $ukupan_period_najma, $iznos_depozita, $ukupno_za_naplati);
        }
        
        if ($stmt->execute()) {
            if (!$isEdit) {
                $rental_id = $conn->insert_id;
            }
            
            $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;
            $uploadErrors = [];
            
            if (isset($_FILES['dokumenti']) && !empty($_FILES['dokumenti']['name'][0])) {
                $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 rent_a_car_dokumenti (rent_a_car_id, uploaded_by, naziv_fajla, putanja, velicina_fajla, mime_type) VALUES (?, ?, ?, ?, ?, ?)");
                            $stmt_ins->bind_param("iissis", $rental_id, $_SESSION['user']['id'], $fileName, $relativePath, $fileSize, $fileType);
                            
                            if (!$stmt_ins->execute()) {
                                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);
            } else {
                $message = $isEdit ? "Najam je uspešno ažuriran." : "Najam je uspešno kreiran.";
                if (!$isEdit) {
                    header("Location: rent_a_car_form.php?id=" . $rental_id);
                    exit;
                } else {
                    $stmt = $conn->prepare("SELECT * FROM rent_a_car WHERE id = ?");
                    $stmt->bind_param("i", $rental_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $rental = $result->fetch_assoc();
                    
                    $stmt = $conn->prepare("SELECT * FROM rent_a_car_dokumenti WHERE rent_a_car_id = ? ORDER BY created_at");
                    $stmt->bind_param("i", $rental_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $existingFiles = $result->fetch_all(MYSQLI_ASSOC);
                }
            }
        } else {
            $error = $isEdit ? "Greška prilikom ažuriranja najma." : "Greška prilikom kreiranja najma.";
        }
    }
}

?>

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

<div class="container main-container mt-4">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card">
                <div class="card-body">
                    <h2 class="card-title mb-4"><?php echo $isEdit ? 'Izmena najma' : 'Novi najam'; ?></h2>
                    
                    <?php if ($message): ?>
                        <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                    <?php endif; ?>
                    
                    <form method="POST" action="" enctype="multipart/form-data">
                        <input type="hidden" name="korisnik_id" value="<?php echo $_SESSION['user']['id']; ?>">
                        <div class="row">
                            <div class="col-md-12">
                                <h5>Podaci o korisniku usluge</h5>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="korisnik_najma" class="form-label">Korisnik najma <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="korisnik_najma" name="korisnik_najma" value="<?php echo htmlspecialchars($rental['korisnik_najma'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="adresa" class="form-label">Adresa <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="adresa" name="adresa" value="<?php echo htmlspecialchars($rental['adresa'] ?? ''); ?>" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($rental['email'] ?? ''); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="telefon" class="form-label">Telefon</label>
                                <input type="text" class="form-control" id="telefon" name="telefon" value="<?php echo htmlspecialchars($rental['telefon'] ?? ''); ?>">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="vozio_preuzeo" class="form-label">Vozio preuzeo <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="vozio_preuzeo" name="vozio_preuzeo" value="<?php echo htmlspecialchars($rental['vozio_preuzeo'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="broj_licne_pasos" class="form-label">Broj lične karte/pasoša <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="broj_licne_pasos" name="broj_licne_pasos" value="<?php echo htmlspecialchars($rental['broj_licne_pasos'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="broj_vozacke" class="form-label">Broj vozačke dozvole <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="broj_vozacke" name="broj_vozacke" value="<?php echo htmlspecialchars($rental['broj_vozacke'] ?? ''); ?>" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="drugi_vozac" class="form-label">Drugi vozač</label>
                                <input type="text" class="form-control" id="drugi_vozac" name="drugi_vozac" value="<?php echo htmlspecialchars($rental['drugi_vozac'] ?? ''); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="drugi_vozac_broj_licne" class="form-label">Broj lične karte/pasoša</label>
                                <input type="text" class="form-control" id="drugi_vozac_broj_licne" name="drugi_vozac_broj_licne" value="<?php echo htmlspecialchars($rental['drugi_vozac_broj_licne'] ?? ''); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="drugi_vozac_broj_vozacke" class="form-label">Broj vozačke dozvole</label>
                                <input type="text" class="form-control" id="drugi_vozac_broj_vozacke" name="drugi_vozac_broj_vozacke" value="<?php echo htmlspecialchars($rental['drugi_vozac_broj_vozacke'] ?? ''); ?>">
                            </div>
                        </div>

                        <div class="row mt-5 mb-3">
                            <div class="col-md-12">
                                <h5>Detalji o najmu vozila</h5>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="tip_marka_vozila" class="form-label">Tip i marka vozila</label>
                                <input type="text" class="form-control" id="tip_marka_vozila" name="tip_marka_vozila" value="<?php echo htmlspecialchars($rental['tip_marka_vozila'] ?? ''); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="registarska_oznaka" class="form-label">Registarska oznaka</label>
                                <input type="text" class="form-control" id="registarska_oznaka" name="registarska_oznaka" value="<?php echo htmlspecialchars($rental['registarska_oznaka'] ?? ''); ?>">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="pocetak_mesto" class="form-label">Početak najma (mesto)</label>
                                <input type="text" class="form-control" id="pocetak_mesto" name="pocetak_mesto" value="<?php echo htmlspecialchars($rental['pocetak_mesto'] ?? ''); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="pocetak_datum" class="form-label">Datum</label>
                                <input type="date" class="form-control" id="pocetak_datum" name="pocetak_datum" value="<?php echo $rental['pocetak_datum'] ?? ''; ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="pocetak_vreme" class="form-label">Vreme</label>
                                <input type="time" class="form-control" id="pocetak_vreme" name="pocetak_vreme" value="<?php echo $rental['pocetak_vreme'] ?? ''; ?>">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="zavrsetak_mesto" class="form-label">Završetak najma (mesto)</label>
                                <input type="text" class="form-control" id="zavrsetak_mesto" name="zavrsetak_mesto" value="<?php echo htmlspecialchars($rental['zavrsetak_mesto'] ?? ''); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="zavrsetak_datum" class="form-label">Datum</label>
                                <input type="date" class="form-control" id="zavrsetak_datum" name="zavrsetak_datum" value="<?php echo $rental['zavrsetak_datum'] ?? ''; ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="zavrsetak_vreme" class="form-label">Vreme</label>
                                <input type="time" class="form-control" id="zavrsetak_vreme" name="zavrsetak_vreme" value="<?php echo $rental['zavrsetak_vreme'] ?? ''; ?>">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Produžetak najma</label>
                                <div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="produzetak_najma" id="produzetak_da" value="da" <?php echo ($rental && $rental['produzetak_najma'] == 'da') ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="produzetak_da">Da</label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="produzetak_najma" id="produzetak_ne" value="ne" <?php echo (!$rental || $rental['produzetak_najma'] == 'ne') ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="produzetak_ne">Ne</label>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="broj_produzenih_dana" class="form-label">Broj produženih dana</label>
                                <input type="number" class="form-control" id="broj_produzenih_dana" name="broj_produzenih_dana" value="<?php echo $rental['broj_produzenih_dana'] ?? 0; ?>" min="0">
                            </div>
                        </div>

                        <div class="row mt-5 mb-3">
                            <div class="col-md-12">
                                <h5>Obračun o najmu vozila</h5>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label for="pocetna_kilometraza" class="form-label">Početna kilometraža</label>
                                <input type="number" step="0.01" class="form-control" id="pocetna_kilometraza" name="pocetna_kilometraza" value="<?php echo $rental['pocetna_kilometraza'] ?? ''; ?>">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="zavrsena_kilometraza" class="form-label">Završena kilometraža</label>
                                <input type="number" step="0.01" class="form-control" id="zavrsena_kilometraza" name="zavrsena_kilometraza" value="<?php echo $rental['zavrsena_kilometraza'] ?? ''; ?>">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="predjena_kilometraza" class="form-label">Pređena kilometraža</label>
                                <input type="number" step="0.01" class="form-control" id="predjena_kilometraza" name="predjena_kilometraza" value="<?php echo $rental['predjena_kilometraza'] ?? ''; ?>" readonly>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="ukupan_period_najma" class="form-label">Ukupan period najma</label>
                                <input type="number" class="form-control" id="ukupan_period_najma" name="ukupan_period_najma" value="<?php echo $rental['ukupan_period_najma'] ?? ''; ?>" readonly>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="dokumenti" class="form-label">Upload fajlova (maksimalno 5)</label>
                            <input type="file" class="form-control" id="dokumenti" name="dokumenti[]" multiple accept=".pdf,.jpg,.jpeg,.png,.gif,.doc,.docx,.xls,.xlsx" onchange="validateFiles(this)">
                            <div id="file-list"></div>
                            <?php if (!empty($existingFiles)): ?>
                                <div class="mt-3">
                                    <label class="form-label">Postojeći fajlovi:</label>
                                    <div class="list-group">
                                        <?php foreach ($existingFiles as $file): ?>
                                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                                <span><i class="bi bi-file-earmark me-2"></i><?php echo htmlspecialchars($file['naziv_fajla']); ?></span>
                                                <a href="<?php echo htmlspecialchars($file['putanja']); ?>" target="_blank" class="btn btn-outline-primary">Pregled</a>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="iznos_depozita" class="form-label">Iznos uplaćenog depozita (RSD)</label>
                                <input type="number" step="0.01" class="form-control" id="iznos_depozita" name="iznos_depozita" value="<?php echo $rental['iznos_depozita'] ?? 0; ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="ukupno_za_naplati" class="form-label">Ukupno za naplatu (RSD)</label>
                                <input type="number" step="0.01" class="form-control" id="ukupno_za_naplati" name="ukupno_za_naplati" value="<?php echo $rental['ukupno_za_naplati'] ?? 0; ?>">
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-between">
                            <a href="rent_a_car.php" class="btn btn-secondary"><i class="bi bi-arrow-left me-1"></i>Nazad</a>
                            <button type="submit" class="btn btn-primary"><?php echo $isEdit ? '<i class="bi bi-floppy me-1"></i>Sačuvaj izmene' : '<i class="bi bi-plus-circle me-1"></i>Kreiraj najam'; ?></button>
                        </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;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const pocetnaKilometraza = document.getElementById('pocetna_kilometraza');
    const zavrsenaKilometraza = document.getElementById('zavrsena_kilometraza');
    const predjenaKilometraza = document.getElementById('predjena_kilometraza');
    
    function calculateKilometraza() {
        const pocetna = parseFloat(pocetnaKilometraza.value) || 0;
        const zavrsena = parseFloat(zavrsenaKilometraza.value) || 0;
        if (pocetna > 0 && zavrsena > 0 && zavrsena >= pocetna) {
            predjenaKilometraza.value = (zavrsena - pocetna).toFixed(2);
        } else {
            predjenaKilometraza.value = '';
        }
    }
    
    pocetnaKilometraza.addEventListener('input', calculateKilometraza);
    zavrsenaKilometraza.addEventListener('input', calculateKilometraza);
    
    const pocetakDatum = document.getElementById('pocetak_datum');
    const zavrsetakDatum = document.getElementById('zavrsetak_datum');
    const brojProduzenihDana = document.getElementById('broj_produzenih_dana');
    const ukupanPeriodNajma = document.getElementById('ukupan_period_najma');
    
    function calculatePeriodNajma() {
        if (pocetakDatum.value && zavrsetakDatum.value) {
            const date1 = new Date(pocetakDatum.value);
            const date2 = new Date(zavrsetakDatum.value);
            const diffTime = Math.abs(date2 - date1);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            const produzenih = parseInt(brojProduzenihDana.value) || 0;
            ukupanPeriodNajma.value = diffDays + produzenih;
        } else {
            const produzenih = parseInt(brojProduzenihDana.value) || 0;
            if (produzenih > 0) {
                ukupanPeriodNajma.value = produzenih;
            } else {
                ukupanPeriodNajma.value = '';
            }
        }
    }
    
    pocetakDatum.addEventListener('change', calculatePeriodNajma);
    zavrsetakDatum.addEventListener('change', calculatePeriodNajma);
    brojProduzenihDana.addEventListener('input', calculatePeriodNajma);
});
</script>

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

