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

requireAdmin();

$success = false;
$error = null;

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    
    $stmt = $conn->prepare("SELECT putanja FROM rent_a_car_dokumenti WHERE rent_a_car_id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    while ($row = $result->fetch_assoc()) {
        if (file_exists(__DIR__ . '/' . $row['putanja'])) {
            unlink(__DIR__ . '/' . $row['putanja']);
        }
    }
    
    $stmt = $conn->prepare("DELETE FROM rent_a_car WHERE id = ?");
    $stmt->bind_param("i", $id);
    
    if ($stmt->execute()) {
        $success = true;
    } else {
        $error = "Greška prilikom brisanja najma.";
    }
}

$stmt = $conn->prepare("
    SELECT 
        r.*,
        COALESCE(d.doc_count, 0) AS doc_count
    FROM rent_a_car r
    LEFT JOIN (
        SELECT rent_a_car_id, COUNT(*) AS doc_count
        FROM rent_a_car_dokumenti
        GROUP BY rent_a_car_id
    ) d ON d.rent_a_car_id = r.id
    ORDER BY r.created_at DESC
");
$stmt->execute();
$rentals = $stmt->get_result();
?>

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

<style>
    .rental-popover {
        max-width: 420px;
    }
    .rental-popover .popover-body {
        white-space: normal;
    }
    .doc-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }
</style>

<div class="container-fluid mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Rent a car</h2>
        <a href="rent_a_car_form.php" class="btn btn-primary">Novi najam</a>
    </div>

    <?php if ($success): ?>
        <div class="alert alert-success">
            Najam je uspešno obrisan.
        </div>
    <?php endif; ?>

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

    <div class="table-responsive">
        <table class="table table-bordered table-hover">
            <thead>
                <tr>
                    <th>Korisnik</th>
                    <th>Vozio preuzeo</th>
                    <th>Tip vozila</th>
                    <th>Registarska oznaka</th>
                    <th>Početak</th>
                    <th>Završetak</th>
                    <th>Za naplatu</th>
                    <th>Datum kreiranja</th>
                    <th class="text-center" width="190px">Akcije</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($rentals->num_rows === 0): ?>
                    <tr>
                        <td colspan="9" class="text-center">Nema najmova</td>
                    </tr>
                <?php else: ?>
                    <?php while ($rental = $rentals->fetch_assoc()): ?>
                        <?php
                        $docCount = (int)($rental['doc_count'] ?? 0);

                        $popoverHtml = '<div class="small">';
                        if (!empty($rental['adresa'])) {
                            $popoverHtml .= '<div><strong>Adresa:</strong> ' . htmlspecialchars($rental['adresa'], ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['broj_licne_pasos'])) {
                            $popoverHtml .= '<div><strong>LK/Pasoš:</strong> ' . htmlspecialchars($rental['broj_licne_pasos'], ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['broj_vozacke'])) {
                            $popoverHtml .= '<div><strong>Vozačka:</strong> ' . htmlspecialchars($rental['broj_vozacke'], ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['telefon'] ?? '')) {
                            $popoverHtml .= '<div><strong>Telefon:</strong> ' . htmlspecialchars(($rental['telefon'] ?? ''), ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['email'] ?? '')) {
                            $popoverHtml .= '<div><strong>Email:</strong> ' . htmlspecialchars(($rental['email'] ?? ''), ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['drugi_vozac'] ?? '')) {
                            $popoverHtml .= '<div><strong>Drugi vozač:</strong> ' . htmlspecialchars(($rental['drugi_vozac'] ?? ''), ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['drugi_vozac_broj_licne'] ?? '')) {
                            $popoverHtml .= '<div><strong>Drugi vozač LK/Pasoš:</strong> ' . htmlspecialchars(($rental['drugi_vozac_broj_licne'] ?? ''), ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['drugi_vozac_broj_vozacke'] ?? '')) {
                            $popoverHtml .= '<div><strong>Drugi vozač vozačka:</strong> ' . htmlspecialchars(($rental['drugi_vozac_broj_vozacke'] ?? ''), ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['pocetak_mesto'] ?? '')) {
                            $popoverHtml .= '<div><strong>Početak (mesto):</strong> ' . htmlspecialchars(($rental['pocetak_mesto'] ?? ''), ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (!empty($rental['zavrsetak_mesto'] ?? '')) {
                            $popoverHtml .= '<div><strong>Završetak (mesto):</strong> ' . htmlspecialchars(($rental['zavrsetak_mesto'] ?? ''), ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (($rental['pocetna_kilometraza'] ?? null) !== null || ($rental['zavrsena_kilometraza'] ?? null) !== null || ($rental['predjena_kilometraza'] ?? null) !== null) {
                            $popoverHtml .= '<div><strong>Kilometraža:</strong> ';
                            $kmParts = [];
                            if (($rental['pocetna_kilometraza'] ?? null) !== null && $rental['pocetna_kilometraza'] !== '') {
                                $kmParts[] = 'početna ' . number_format((float)$rental['pocetna_kilometraza'], 2);
                            }
                            if (($rental['zavrsena_kilometraza'] ?? null) !== null && $rental['zavrsena_kilometraza'] !== '') {
                                $kmParts[] = 'završna ' . number_format((float)$rental['zavrsena_kilometraza'], 2);
                            }
                            if (($rental['predjena_kilometraza'] ?? null) !== null && $rental['predjena_kilometraza'] !== '') {
                                $kmParts[] = 'pređena ' . number_format((float)$rental['predjena_kilometraza'], 2);
                            }
                            $popoverHtml .= htmlspecialchars(implode(', ', $kmParts), ENT_QUOTES, 'UTF-8') . '</div>';
                        }
                        if (($rental['ukupan_period_najma'] ?? null) !== null && $rental['ukupan_period_najma'] !== '') {
                            $popoverHtml .= '<div><strong>Period najma:</strong> ' . (int)$rental['ukupan_period_najma'] . ' dana</div>';
                        }
                        if (!empty($rental['produzetak_najma'])) {
                            $popoverHtml .= '<div><strong>Produžetak:</strong> ' . htmlspecialchars($rental['produzetak_najma'], ENT_QUOTES, 'UTF-8');
                            $popoverHtml .= ' <span class="text-muted">(' . (int)($rental['broj_produzenih_dana'] ?? 0) . ' dana)</span></div>';
                        }
                        if (!empty($rental['iznos_depozita'])) {
                            $popoverHtml .= '<div><strong>Depozit:</strong> ' . number_format((float)$rental['iznos_depozita'], 2) . ' RSD</div>';
                        }
                        if ($docCount > 0) {
                            $popoverHtml .= '<div><strong>Dokumenti:</strong> ' . $docCount . '</div>';
                        }
                        $popoverHtml .= '</div>';
                        ?>
                        <tr>
                            <td><?php echo htmlspecialchars($rental['korisnik_najma'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($rental['vozio_preuzeo']); ?></td>
                            <td><?php echo htmlspecialchars($rental['tip_marka_vozila'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($rental['registarska_oznaka'] ?? '-'); ?></td>
                            <td>
                                <?php 
                                if ($rental['pocetak_datum']) {
                                    echo date('d.m.Y', strtotime($rental['pocetak_datum']));
                                    if ($rental['pocetak_vreme']) {
                                        echo ' ' . date('H:i', strtotime($rental['pocetak_vreme']));
                                    }
                                } else {
                                    echo '-';
                                }
                                ?>
                            </td>
                            <td>
                                <?php 
                                if ($rental['zavrsetak_datum']) {
                                    echo date('d.m.Y', strtotime($rental['zavrsetak_datum']));
                                    if ($rental['zavrsetak_vreme']) {
                                        echo ' ' . date('H:i', strtotime($rental['zavrsetak_vreme']));
                                    }
                                } else {
                                    echo '-';
                                }
                                ?>
                            </td>
                            <td><?php echo number_format($rental['ukupno_za_naplati'], 2); ?> RSD</td>
                            <td><?php echo date('d.m.Y H:i', strtotime($rental['created_at'])); ?></td>
                            <td class="text-center">
                                <div class="btn-group">
                                    <button
                                        type="button"
                                        class="btn btn-outline-secondary"
                                        data-bs-toggle="popover"
                                        data-bs-trigger="hover focus"
                                        data-bs-placement="left"
                                        data-bs-html="true"
                                        data-bs-custom-class="rental-popover"
                                        data-bs-title="<?php echo htmlspecialchars('Detalji najma', ENT_QUOTES, 'UTF-8'); ?>"
                                        data-bs-content="<?php echo htmlspecialchars($popoverHtml, ENT_QUOTES, 'UTF-8'); ?>"
                                    ><i class="bi bi-eye"></i></button>

                                    <?php if ($docCount > 0): ?>
                                        <a href="rent_a_car_form.php?id=<?php echo $rental['id']; ?>#dokumenti" class="btn btn-outline-success doc-btn" title="Dokumenti (<?php echo $docCount; ?>)">
                                            <i class="bi bi-paperclip"></i>
                                        </a>
                                    <?php else: ?>
                                        <button type="button" class="btn btn-outline-secondary doc-btn" title="Nema dokumenata" disabled><i class="bi bi-paperclip"></i></button>
                                    <?php endif; ?>

                                    <a href="rent_a_car_form.php?id=<?php echo $rental['id']; ?>" class="btn btn-dark"><i class="bi bi-pencil-square"></i></a>
                                    <a href="?delete=<?php echo $rental['id']; ?>" class="btn btn-danger" onclick="return confirm('Da li ste sigurni da želite da obrišete ovaj najam?')"><i class="bi bi-trash"></i></a>
                                </div>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const triggers = document.querySelectorAll('[data-bs-toggle="popover"]');
    triggers.forEach((el) => new bootstrap.Popover(el));
});
</script>

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

