<?php
require __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$branch = $_POST['branch_code'] ?? '';
$agreement = trim($_POST['agreement_no'] ?? '');
$rentalDate = trim($_POST['rental_date'] ?? '');
$employeeName = trim($_POST['employee_name'] ?? '');
$waitTime = $_POST['wait_time'] ?? '';
$processTime = $_POST['process_time'] ?? '';
$officeFind = (int)($_POST['office_find_rating'] ?? 0);
$pickupSpeed = (int)($_POST['pickup_speed_rating'] ?? 0);
$staff = (int)($_POST['staff_rating'] ?? 0);
$professionalism = (int)($_POST['professionalism_rating'] ?? 0);
$terms = (int)($_POST['terms_rating'] ?? 0);
$vehicleCondition = (int)($_POST['vehicle_condition_rating'] ?? 0);
$cleanliness = (int)($_POST['cleanliness_rating'] ?? 0);
$overall = (int)($_POST['overall_rating'] ?? 0);
$rentAgain = isset($_POST['rent_again']) ? (int)$_POST['rent_again'] : -1;
$comment = trim($_POST['comment'] ?? '');
$website = trim($_POST['website'] ?? '');
$formStartedAt = (int)($_POST['form_started_at'] ?? 0);

$allowedWait = ['0–5 min','6–10 min','11–20 min','21–30 min','More than 30 min'];
$allowedProcess = ['Less than 5 min','5–10 min','11–15 min','16–20 min','More than 20 min'];

$errors = [];
if (!isset($branches[$branch])) $errors[] = 'Please select your pick-up location.';
if ($agreement !== '' && mb_strlen($agreement) > 60) $errors[] = 'Agreement number is too long.';
if ($rentalDate !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $rentalDate)) $errors[] = 'Rental date is not valid.';
if ($employeeName !== '' && mb_strlen($employeeName) > 120) $errors[] = 'Team member name is too long.';
if (!in_array($waitTime, $allowedWait, true)) $errors[] = 'Please select waiting time.';
if (!in_array($processTime, $allowedProcess, true)) $errors[] = 'Please select rental process time.';
foreach ([$officeFind, $pickupSpeed, $staff, $professionalism, $terms, $vehicleCondition, $cleanliness, $overall] as $rating) {
    if ($rating < 1 || $rating > 5) $errors[] = 'Please answer all rating questions.';
}
if (!in_array($rentAgain, [0,1], true)) $errors[] = 'Please answer whether you would rent from Avia again.';
if (mb_strlen($comment) > 1500) $errors[] = 'Comment is too long.';

// Simple bot protection for a public static survey URL.
if ($website !== '') {
    header('Location: thank-you.php');
    exit;
}
if ($formStartedAt > 0 && (time() - $formStartedAt) < 2) {
    $errors[] = 'Please review your answers and try again.';
}

if ($errors) {
    http_response_code(422);
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="style.css"><title>Avia feedback</title></head><body><main class="survey-shell"><section class="survey-card state-box"><h2>We could not save your feedback.</h2><p>' . e(implode(' ', array_unique($errors))) . '</p><p><a href="javascript:history.back()">Go back</a></p></section></main></body></html>';
    exit;
}

$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$ipHash = $ip !== '' ? hash('sha256', $ip . '|avia-feedback-v3') : null;

try {
    $stmt = $pdo->prepare('INSERT INTO reviews
        (branch_code, agreement_no, rental_date, employee_name,
         wait_time, process_time, office_find_rating, pickup_speed_rating, staff_rating, professionalism_rating,
         terms_rating, vehicle_condition_rating, cleanliness_rating, overall_rating, rent_again, comment, ip_hash)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
    $stmt->execute([
        $branch,
        $agreement !== '' ? $agreement : null,
        $rentalDate !== '' ? $rentalDate : null,
        $employeeName !== '' ? $employeeName : null,
        $waitTime,
        $processTime,
        $officeFind,
        $pickupSpeed,
        $staff,
        $professionalism,
        $terms,
        $vehicleCondition,
        $cleanliness,
        $overall,
        $rentAgain,
        $comment !== '' ? $comment : null,
        $ipHash
    ]);
} catch (PDOException $e) {
    if ((int)$e->errorInfo[1] === 1062 && $agreement !== '') {
        header('Location: thank-you.php?already=1');
        exit;
    }
    http_response_code(500);
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="style.css"><title>Avia feedback</title></head><body><main class="survey-shell"><section class="survey-card state-box"><h2>Feedback could not be saved.</h2><p>Please try again.</p><p><a href="javascript:history.back()">Go back</a></p></section></main></body></html>';
    exit;
}

header('Location: thank-you.php');
exit;
