<?php
require __DIR__ . '/config.php';
require_existing_admin();

$branchFilter = $_GET['branch'] ?? '';
$employeeFilter = trim($_GET['employee'] ?? '');
$dateFrom = $_GET['from'] ?? date('Y-m-01');
$dateTo = $_GET['to'] ?? date('Y-m-d');

$where = ['DATE(r.created_at) BETWEEN ? AND ?'];
$params = [$dateFrom, $dateTo];
if ($branchFilter !== '' && isset($branches[$branchFilter])) {
    $where[] = 'r.branch_code = ?';
    $params[] = $branchFilter;
}
if ($employeeFilter !== '') {
    $where[] = 'r.employee_name = ?';
    $params[] = $employeeFilter;
}
$whereSql = implode(' AND ', $where);

$stmt = $pdo->prepare("SELECT COUNT(*) reviews_count,
    ROUND(AVG(overall_rating),2) avg_overall,
    ROUND(AVG(staff_rating),2) avg_staff,
    ROUND(AVG(professionalism_rating),2) avg_professionalism,
    ROUND(AVG(cleanliness_rating),2) avg_cleanliness,
    ROUND(AVG(office_find_rating),2) avg_find,
    ROUND(100 * AVG(rent_again),1) rent_again_pct
    FROM reviews r WHERE $whereSql");
$stmt->execute($params);
$summary = $stmt->fetch();

$stmt = $pdo->prepare("SELECT r.* FROM reviews r WHERE $whereSql ORDER BY r.created_at DESC LIMIT 500");
$stmt->execute($params);
$reviews = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT branch_code, COUNT(*) reviews_count,
    ROUND(AVG(overall_rating),2) avg_overall,
    ROUND(AVG(staff_rating),2) avg_staff,
    ROUND(AVG(professionalism_rating),2) avg_professionalism,
    ROUND(AVG(cleanliness_rating),2) avg_cleanliness,
    ROUND(100 * AVG(rent_again),1) rent_again_pct
    FROM reviews r
    WHERE DATE(r.created_at) BETWEEN ? AND ?
    GROUP BY branch_code
    ORDER BY avg_overall DESC, reviews_count DESC");
$stmt->execute([$dateFrom, $dateTo]);
$branchStats = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT employee_name, COUNT(*) reviews_count,
    ROUND(AVG(staff_rating),2) avg_staff,
    ROUND(AVG(professionalism_rating),2) avg_professionalism,
    ROUND(AVG(overall_rating),2) avg_overall,
    ROUND(100 * AVG(rent_again),1) rent_again_pct
    FROM reviews r
    WHERE DATE(r.created_at) BETWEEN ? AND ?
      AND employee_name IS NOT NULL AND employee_name <> ''
    GROUP BY employee_name
    ORDER BY avg_staff DESC, reviews_count DESC");
$stmt->execute([$dateFrom, $dateTo]);
$employeeStats = $stmt->fetchAll();

$employees = $pdo->query("SELECT DISTINCT employee_name FROM reviews WHERE employee_name IS NOT NULL AND employee_name <> '' ORDER BY employee_name")->fetchAll(PDO::FETCH_COLUMN);
$queryForExport = http_build_query(['branch'=>$branchFilter,'employee'=>$employeeFilter,'from'=>$dateFrom,'to'=>$dateTo]);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Avia – Recenzije kupaca</title>
<link rel="stylesheet" href="style.css">
</head>
<body class="admin-body">
<main class="admin-shell">
    <nav class="admin-breadcrumb"><a href="admin.php">Administracija</a><span>›</span><strong>Recenzije kupaca</strong></nav>
    <header class="admin-topbar">
        <div><div class="brand">AVIA</div><h1>Recenzije kupaca</h1><p>Ocjene iskustva najma po poslovnicama i djelatnicima</p></div>
        <div class="admin-actions"><a class="admin-back-button" href="admin.php">← Administracija</a><a class="secondary-button" href="export.php?<?= e($queryForExport) ?>">Izvoz u Excel</a></div>
    </header>

    <section class="admin-panel static-link-panel">
        <div class="panel-title"><div><h2>Stalni link ankete</h2><p>Isti link šalje se svim strankama iz postojećeg Avia sustava.</p></div></div>
        <div class="permanent-link"><code><?= e((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/avia-feedback/admin.php'), '/.') . '/index.php') ?></code></div>
    </section>

    <form class="admin-filters" method="get">
        <select name="branch"><option value="">Sve poslovnice</option><?php foreach ($branches as $code=>$name): ?><option value="<?= e($code) ?>" <?= $branchFilter===$code?'selected':'' ?>><?= e($name) ?></option><?php endforeach; ?></select>
        <select name="employee"><option value="">Svi imenovani djelatnici</option><?php foreach ($employees as $employee): ?><option value="<?= e($employee) ?>" <?= $employeeFilter===$employee?'selected':'' ?>><?= e($employee) ?></option><?php endforeach; ?></select>
        <input type="date" name="from" value="<?= e($dateFrom) ?>">
        <input type="date" name="to" value="<?= e($dateTo) ?>">
        <button type="submit">Primijeni filtre</button>
    </form>

    <section class="metric-grid">
        <article><span>Recenzije</span><strong><?= (int)$summary['reviews_count'] ?></strong></article>
        <article><span>Ukupna ocjena</span><strong><?= $summary['avg_overall'] ?? '—' ?><small>/5</small></strong></article>
        <article><span>Ljubaznost i pomoć</span><strong><?= $summary['avg_staff'] ?? '—' ?><small>/5</small></strong></article>
        <article><span>Profesionalnost</span><strong><?= $summary['avg_professionalism'] ?? '—' ?><small>/5</small></strong></article>
        <article><span>Čistoća vozila</span><strong><?= $summary['avg_cleanliness'] ?? '—' ?><small>/5</small></strong></article>
        <article><span>Ponovno bi unajmili</span><strong><?= $summary['rent_again_pct'] !== null ? e($summary['rent_again_pct']).'%' : '—' ?></strong></article>
    </section>

    <div class="admin-grid-two">
        <section class="admin-panel">
            <div class="panel-title"><div><h2>Poslovnice</h2><p>Prosječna ukupna ocjena</p></div></div>
            <div class="bar-chart">
                <?php if (!$branchStats): ?><p class="empty">No feedback in selected period.</p><?php endif; ?>
                <?php foreach ($branchStats as $r): $pct = ((float)$r['avg_overall']/5)*100; ?>
                    <div class="bar-row"><div class="bar-label"><span><?= e($branches[$r['branch_code']] ?? $r['branch_code']) ?></span><small><?= (int)$r['reviews_count'] ?> reviews</small></div><div class="bar-track"><div class="bar-fill" style="width:<?= max(0,min(100,$pct)) ?>%"></div></div><strong><?= e($r['avg_overall']) ?></strong></div>
                <?php endforeach; ?>
            </div>
        </section>

        <section class="admin-panel">
            <div class="panel-title"><div><h2>Imenovani djelatnici</h2><p>Prikaz samo kada je stranka navela ime djelatnika</p></div></div>
            <div class="bar-chart">
                <?php if (!$employeeStats): ?><p class="empty">No customers have entered a team member name yet.</p><?php endif; ?>
                <?php foreach ($employeeStats as $r): $pct = ((float)$r['avg_staff']/5)*100; ?>
                    <div class="bar-row"><div class="bar-label"><span><?= e($r['employee_name']) ?></span><small><?= (int)$r['reviews_count'] ?> reviews</small></div><div class="bar-track"><div class="bar-fill alt" style="width:<?= max(0,min(100,$pct)) ?>%"></div></div><strong><?= e($r['avg_staff']) ?></strong></div>
                <?php endforeach; ?>
            </div>
        </section>
    </div>

    <section class="admin-panel">
        <div class="panel-title"><div><h2>Usporedba poslovnica</h2><p>Operativni pregled</p></div></div>
        <div class="table-wrap"><table>
            <thead><tr><th>Branch</th><th>Reviews</th><th>Friendly/helpful</th><th>Professional</th><th>Cleanliness</th><th>Overall</th><th>Rent again</th></tr></thead>
            <tbody><?php foreach ($branchStats as $r): ?><tr><td><?= e($branches[$r['branch_code']] ?? $r['branch_code']) ?></td><td><?= (int)$r['reviews_count'] ?></td><td><?= e($r['avg_staff']) ?></td><td><?= e($r['avg_professionalism']) ?></td><td><?= e($r['avg_cleanliness']) ?></td><td><strong><?= e($r['avg_overall']) ?></strong></td><td><?= e($r['rent_again_pct']) ?>%</td></tr><?php endforeach; ?></tbody>
        </table></div>
    </section>

    <section class="admin-panel">
        <div class="panel-title"><div><h2>Najnovije recenzije</h2><p>Do 500 rezultata prema odabranim filtrima</p></div></div>
        <div class="table-wrap"><table class="feedback-table">
            <thead><tr><th>Submitted</th><th>Branch</th><th>Agreement</th><th>Rental date</th><th>Team member</th><th>Wait</th><th>Process</th><th>Find office</th><th>Pickup</th><th>Friendly</th><th>Professional</th><th>Terms</th><th>Vehicle</th><th>Clean</th><th>Overall</th><th>Again</th><th>Comment</th></tr></thead>
            <tbody><?php foreach ($reviews as $r): ?><tr>
                <td><?= e($r['created_at']) ?></td>
                <td><?= e($branches[$r['branch_code']] ?? $r['branch_code']) ?></td>
                <td><?= e($r['agreement_no'] ?: '—') ?></td>
                <td><?= e($r['rental_date'] ?: '—') ?></td>
                <td><?= e($r['employee_name'] ?: '—') ?></td>
                <td><?= e($r['wait_time']) ?></td><td><?= e($r['process_time']) ?></td>
                <td><?= (int)$r['office_find_rating'] ?>/5</td><td><?= (int)$r['pickup_speed_rating'] ?>/5</td><td><?= (int)$r['staff_rating'] ?>/5</td><td><?= (int)$r['professionalism_rating'] ?>/5</td><td><?= (int)$r['terms_rating'] ?>/5</td><td><?= (int)$r['vehicle_condition_rating'] ?>/5</td><td><?= (int)$r['cleanliness_rating'] ?>/5</td><td><strong><?= (int)$r['overall_rating'] ?>/5</strong></td><td><?= $r['rent_again'] ? 'Yes' : 'No' ?></td><td class="comment-cell"><?= nl2br(e($r['comment'] ?? '')) ?></td>
            </tr><?php endforeach; ?></tbody>
        </table></div>
    </section>
</main>
</body>
</html>
