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

$selected_year  = isset($_GET['year'])  ? (int)$_GET['year']  : date('Y');
$selected_month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');

$start_date = date('Y-m-01', mktime(0, 0, 0, $selected_month, 1, $selected_year));
$end_date   = date('Y-m-t',  mktime(0, 0, 0, $selected_month, 1, $selected_year));

$months = [
    1=>'Januar',2=>'Februar',3=>'Mart',4=>'April',5=>'Maj',6=>'Jun',
    7=>'Jul',8=>'Avgust',9=>'Septembar',10=>'Oktobar',11=>'Novembar',12=>'Decembar'
];

$summary_query = "
    SELECT
        u.id,
        u.name          AS vozac_ime,
        COUNT(v.id)     AS broj_voznji,
        SUM(v.cena)     AS ukupna_cena,
        SUM(v.troskovi) AS ukupni_troskovi
    FROM users u
    LEFT JOIN voznje v ON v.vozac_id = u.id
        AND v.datum BETWEEN ? AND ?
        AND v.status != 'Obrisano'
    WHERE u.role = 'vozac' AND u.active = 1
    GROUP BY u.id, u.name
    ORDER BY broj_voznji DESC, u.name ASC
";

$rides_query = "
    SELECT
        v.id,
        v.datum,
        v.vreme,
        v.polazna_adresa,
        v.dolazna_adresa,
        v.ime_klijenta,
        v.cena,
        v.troskovi,
        v.status,
        v.vozac_id,
        k.naziv AS komitent_naziv
    FROM voznje v
    LEFT JOIN komitenti k ON v.komitent_id = k.id
    WHERE v.datum BETWEEN ? AND ?
        AND v.status != 'Obrisano'
        AND v.vozac_id IS NOT NULL
    ORDER BY v.datum ASC, v.vreme ASC
";

if (isset($_GET['export']) && $_GET['export'] === 'excel_vozac' && isset($_GET['vozac_id'])) {
    $vozac_id = (int)$_GET['vozac_id'];

    $stmt_name = $conn->prepare("SELECT name FROM users WHERE id = ? AND role = 'vozac'");
    $stmt_name->bind_param("i", $vozac_id);
    $stmt_name->execute();
    $vozac_row = $stmt_name->get_result()->fetch_assoc();
    $vozac_name = $vozac_row ? $vozac_row['name'] : 'vozac';

    $stmt = $conn->prepare("
        SELECT v.datum, v.vreme, v.polazna_adresa, v.dolazna_adresa,
               v.ime_klijenta, k.naziv AS komitent_naziv,
               v.cena, v.troskovi, v.status
        FROM voznje v
        LEFT JOIN komitenti k ON v.komitent_id = k.id
        WHERE v.datum BETWEEN ? AND ?
            AND v.vozac_id = ?
            AND v.status != 'Obrisano'
        ORDER BY v.datum ASC, v.vreme ASC
    ");
    $stmt->bind_param("ssi", $start_date, $end_date, $vozac_id);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    $safe_name = preg_replace('/[^a-zA-Z0-9_-]/', '_', $vozac_name);
    $filename  = 'voznje_' . $safe_name . '_' . $selected_year . '_' . str_pad($selected_month, 2, '0', STR_PAD_LEFT) . '.xls';
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: max-age=0');

    $xe = fn($v) => htmlspecialchars((string)$v, ENT_XML1, 'UTF-8');

    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">' . "\n";
    echo '<Worksheet ss:Name="Voznje"><Table>' . "\n";
    echo '<Row>';
    foreach (['Datum','Vreme','Polazna adresa','Dolazna adresa','Ime klijenta','Komitent','Cena (RSD)','Troškovi (RSD)','Status'] as $h)
        echo '<Cell><Data ss:Type="String">' . $xe($h) . '</Data></Cell>';
    echo '</Row>' . "\n";
    foreach ($rows as $r) {
        echo '<Row>';
        foreach ([
            $r['datum'] ?? '', $r['vreme'] ?? '',
            $r['polazna_adresa'] ?? '', $r['dolazna_adresa'] ?? '',
            $r['ime_klijenta'] ?? '', $r['komitent_naziv'] ?? '',
            $r['cena'] ?? '', $r['troskovi'] ?? '', $r['status'] ?? ''
        ] as $v)
            echo '<Cell><Data ss:Type="String">' . $xe($v) . '</Data></Cell>';
        echo '</Row>' . "\n";
    }
    echo '</Table></Worksheet></Workbook>';
    exit;
}

if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    $stmt = $conn->prepare($summary_query);
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    $filename = 'statistika_vozaci_' . $selected_year . '_' . str_pad($selected_month, 2, '0', STR_PAD_LEFT) . '.xls';
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: max-age=0');

    $xe = fn($v) => htmlspecialchars((string)$v, ENT_XML1, 'UTF-8');

    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">' . "\n";
    echo '<Worksheet ss:Name="Statistika vozaca"><Table>' . "\n";
    echo '<Row>';
    foreach (['Vozač','Broj vožnji','Ukupna cena (RSD)','Troškovi (RSD)','Zarada (RSD)'] as $h)
        echo '<Cell><Data ss:Type="String">' . $xe($h) . '</Data></Cell>';
    echo '</Row>' . "\n";
    foreach ($rows as $row) {
        $cena   = floatval($row['ukupna_cena']     ?? 0);
        $tros   = floatval($row['ukupni_troskovi'] ?? 0);
        echo '<Row>';
        foreach ([$row['vozac_ime'], $row['broj_voznji'], number_format($cena,2,'.',''), number_format($tros,2,'.',''), number_format($cena-$tros,2,'.', '')] as $v)
            echo '<Cell><Data ss:Type="String">' . $xe($v) . '</Data></Cell>';
        echo '</Row>' . "\n";
    }
    echo '</Table></Worksheet></Workbook>';
    exit;
}

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $stmt = $conn->prepare($summary_query);
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=statistika_vozaci_' . $selected_year . '_' . str_pad($selected_month, 2, '0', STR_PAD_LEFT) . '.csv');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, ['Vozač','Broj vožnji','Ukupna cena (RSD)','Troškovi (RSD)','Zarada (RSD)'], ',', '"', '\\');
    foreach ($rows as $row) {
        $cena = floatval($row['ukupna_cena'] ?? 0);
        $tros = floatval($row['ukupni_troskovi'] ?? 0);
        fputcsv($out, [$row['vozac_ime'], $row['broj_voznji'], number_format($cena,2,'.',''), number_format($tros,2,'.',''), number_format($cena-$tros,2,'.','')], ',', '"', '\\');
    }
    fclose($out);
    exit;
}

$stmt = $conn->prepare($summary_query);
$stmt->bind_param("ss", $start_date, $end_date);
$stmt->execute();
$summary = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$stmt2 = $conn->prepare($rides_query);
$stmt2->bind_param("ss", $start_date, $end_date);
$stmt2->execute();
$all_rides_raw = $stmt2->get_result()->fetch_all(MYSQLI_ASSOC);

$rides_by_vozac = [];
foreach ($all_rides_raw as $r) {
    $rides_by_vozac[$r['vozac_id']][] = $r;
}

$current_year = date('Y');
$years = range($current_year - 5, $current_year + 1);
?>

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

<div class="container-fluid mt-4">
    <div class="card">
        <div class="card-header">
            <h3 class="card-title mb-0">
                <i class="bi bi-person-badge me-2"></i>
                Statistika vozača - po mesecima
            </h3>
        </div>
        <div class="card-body">
            <form method="get" class="row g-3 mb-4">
                <div class="col-md-3">
                    <label for="year" class="form-label">Godina</label>
                    <select class="form-select" id="year" name="year">
                        <?php foreach ($years as $year): ?>
                            <option value="<?php echo $year; ?>" <?php echo $year == $selected_year ? 'selected' : ''; ?>>
                                <?php echo $year; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="month" class="form-label">Mesec</label>
                    <select class="form-select" id="month" name="month">
                        <?php foreach ($months as $num => $name): ?>
                            <option value="<?php echo $num; ?>" <?php echo $num == $selected_month ? 'selected' : ''; ?>>
                                <?php echo $name; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 d-flex align-items-end gap-2">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search me-2"></i>Prikaži
                    </button>
                    <a href="?year=<?php echo $selected_year; ?>&month=<?php echo $selected_month; ?>&export=csv" class="btn btn-success">
                        <i class="bi bi-download me-2"></i>Export CSV
                    </a>
                    <a href="?year=<?php echo $selected_year; ?>&month=<?php echo $selected_month; ?>&export=excel" class="btn btn-outline-success">
                        <i class="bi bi-file-earmark-excel me-2"></i>Export Excel
                    </a>
                </div>
            </form>

            <div class="alert alert-info">
                <i class="bi bi-info-circle me-2"></i>
                Prikazuju se vožnje za <strong><?php echo $months[$selected_month]; ?> <?php echo $selected_year; ?></strong>
            </div>

            <?php
            $grand_cena   = 0;
            $grand_tros   = 0;
            $grand_voznji = 0;
            foreach ($summary as $r) {
                $grand_cena   += floatval($r['ukupna_cena']     ?? 0);
                $grand_tros   += floatval($r['ukupni_troskovi'] ?? 0);
                $grand_voznji += intval($r['broj_voznji']);
            }
            ?>

            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>Vozač</th>
                            <th class="text-center">Broj vožnji</th>
                            <th class="text-end">Ukupna cena</th>
                            <th class="text-end">Troškovi</th>
                            <th class="text-end">Zarada</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($summary as $row):
                            $cena   = floatval($row['ukupna_cena']     ?? 0);
                            $tros   = floatval($row['ukupni_troskovi'] ?? 0);
                            $zarada = $cena - $tros;
                        ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['vozac_ime']); ?></td>
                            <td class="text-center"><?php echo $row['broj_voznji']; ?></td>
                            <td class="text-end"><?php echo number_format($cena, 2, ',', '.'); ?> RSD</td>
                            <td class="text-end"><?php echo $tros > 0 ? number_format($tros, 2, ',', '.') . ' RSD' : '-'; ?></td>
                            <td class="text-end"><?php echo number_format($zarada, 2, ',', '.'); ?> RSD</td>
                            <td class="text-center">
                                <?php if (!empty($rides_by_vozac[$row['id']])): ?>
                                    <button class="btn btn-sm btn-outline-primary vozac-link"
                                            data-vozac-id="<?php echo $row['id']; ?>"
                                            data-vozac-ime="<?php echo htmlspecialchars($row['vozac_ime']); ?>">
                                        <i class="bi bi-list-ul"></i>
                                    </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="table-info fw-bold">
                            <td>Ukupno</td>
                            <td class="text-center"><?php echo $grand_voznji; ?></td>
                            <td class="text-end"><?php echo number_format($grand_cena, 2, ',', '.'); ?> RSD</td>
                            <td class="text-end"><?php echo number_format($grand_tros, 2, ',', '.'); ?> RSD</td>
                            <td class="text-end"><?php echo number_format($grand_cena - $grand_tros, 2, ',', '.'); ?> RSD</td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="vozacModal" tabindex="-1">
    <div class="modal-dialog modal-fullscreen-lg-down" style="max-width:95vw">
        <div class="modal-content">
            <div class="modal-header py-2">
                <h5 class="modal-title" id="vozacModalTitle"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover table-sm mb-0" id="vozacModalTable" style="font-size:0.875rem">
                        <thead class="table-dark">
                            <tr>
                                <th style="width:90px;white-space:nowrap">Datum</th>
                                <th style="width:60px;white-space:nowrap">Vreme</th>
                                <th>Polazna adresa</th>
                                <th>Dolazna adresa</th>
                                <th style="width:140px">Ime klijenta</th>
                                <th style="width:120px">Komitent</th>
                                <th style="width:110px" class="text-end">Cena</th>
                                <th style="width:110px" class="text-end">Troškovi</th>
                                <th style="width:90px" class="text-center">Status</th>
                            </tr>
                        </thead>
                        <tbody id="vozacModalBody"></tbody>
                        <tfoot id="vozacModalFoot"></tfoot>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <a id="vozacExportBtn" href="#" class="btn btn-outline-success">
                    <i class="bi bi-file-earmark-excel me-1"></i>Export Excel
                </a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Zatvori</button>
            </div>
        </div>
    </div>
</div>

<script>
const ridesData = <?php echo json_encode($rides_by_vozac, JSON_UNESCAPED_UNICODE); ?>;

const statusClass = {
    'Završeno': 'success',
    'Predstoji': 'warning',
    'Na čekanju': 'info'
};

document.querySelectorAll('.vozac-link').forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        const id   = this.dataset.vozacId;
        const ime  = this.dataset.vozacIme;
        const rows = ridesData[id] || [];

        document.getElementById('vozacModalTitle').textContent = ime;
        document.getElementById('vozacExportBtn').href =
            `?year=<?php echo $selected_year; ?>&month=<?php echo $selected_month; ?>&export=excel_vozac&vozac_id=${id}`;

        let tbody = '';
        let totalCena = 0, totalTros = 0;

        const addr = s => s
            ? `<span title="${s.replace(/"/g,'&quot;')}" style="display:block;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${s}</span>`
            : '-';

        rows.forEach(function(r) {
            const cena = parseFloat(r.cena || 0);
            const tros = parseFloat(r.troskovi || 0);
            totalCena += cena;
            totalTros += tros;

            const sc = statusClass[r.status] || 'secondary';
            tbody += `<tr>
                <td style="white-space:nowrap">${r.datum ? new Date(r.datum).toLocaleDateString('sr-RS') : ''}</td>
                <td style="white-space:nowrap">${r.vreme ? r.vreme.substring(0,5) : ''}</td>
                <td style="max-width:220px">${addr(r.polazna_adresa)}</td>
                <td style="max-width:220px">${addr(r.dolazna_adresa)}</td>
                <td>${r.ime_klijenta || '-'}</td>
                <td>${r.komitent_naziv || '-'}</td>
                <td class="text-end" style="white-space:nowrap">${cena > 0 ? cena.toLocaleString('sr-RS', {minimumFractionDigits:2}) + ' RSD' : '-'}</td>
                <td class="text-end" style="white-space:nowrap">${tros > 0 ? tros.toLocaleString('sr-RS', {minimumFractionDigits:2}) + ' RSD' : '-'}</td>
                <td class="text-center"><span class="badge bg-${sc}">${r.status || ''}</span></td>
            </tr>`;
        });

        const fmt = v => v.toLocaleString('sr-RS', {minimumFractionDigits:2}) + ' RSD';
        const tfoot = `<tr class="table-info fw-bold">
            <td colspan="6" class="text-end">Ukupno (${rows.length} vožnji):</td>
            <td class="text-end">${fmt(totalCena)}</td>
            <td class="text-end">${totalTros > 0 ? fmt(totalTros) : '-'}</td>
            <td></td>
        </tr>`;

        document.getElementById('vozacModalBody').innerHTML = tbody;
        document.getElementById('vozacModalFoot').innerHTML = tfoot;

        new bootstrap.Modal(document.getElementById('vozacModal')).show();
    });
});
</script>

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