<?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; }

$stmt = $pdo->prepare('SELECT r.* FROM reviews r WHERE '.implode(' AND ',$where).' ORDER BY r.created_at DESC');
$stmt->execute($params);
$rows = $stmt->fetchAll();

$filename = 'avia-feedback-' . date('Y-m-d-His') . '.csv';
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo "\xEF\xBB\xBF";
$out = fopen('php://output', 'w');
$sep = ';';
fputcsv($out, ['Submitted','Branch','Agreement','Rental date','Team member','Wait time','Rental process time','Easy to find office','Pickup speed','Friendly & helpful','Professionalism','Terms clarity','Vehicle condition','Vehicle cleanliness','Overall','Would rent again','Comment'], $sep);
foreach ($rows as $r) {
    fputcsv($out, [
        $r['created_at'], $branches[$r['branch_code']] ?? $r['branch_code'], $r['agreement_no'], $r['rental_date'], $r['employee_name'],
        $r['wait_time'], $r['process_time'], $r['office_find_rating'], $r['pickup_speed_rating'], $r['staff_rating'], $r['professionalism_rating'],
        $r['terms_rating'], $r['vehicle_condition_rating'], $r['cleanliness_rating'], $r['overall_rating'], $r['rent_again'] ? 'Yes' : 'No', $r['comment']
    ], $sep);
}
fclose($out);
exit;
