<?php
declare(strict_types=1);
if (!defined('STORE_ROOT')) { http_response_code(403); exit; }
function reviewHandler(string $action, array $in): void { if ($action === 'submit') { Security::enforceCSRF(); $uid = App::requireAuth(); $rating = (int)($in['rating'] ?? 0); $title = trim($in['title'] ?? ''); $body = trim($in['body'] ?? ''); if ($rating < 1 || $rating > 5 || !$body) { echo json_encode(['success' => false, 'error' => 'Valid rating and review body are required.', 'csrf' => Auth::regenerateCsrf()]); exit; } $storeId = App::storeId(); try { $isVerified = 0; $hasCode = DB::one("SELECT id, order_id FROM review_codes WHERE user_id = :uid AND used = 0 AND (expires_at IS NULL OR expires_at > NOW()) LIMIT 1", [':uid' => $uid]); if ($hasCode) { $isVerified = 1; DB::run("UPDATE review_codes SET used = 1, credited = 1 WHERE id = :id AND used = 0", [':id' => $hasCode['id']]); $affected = DB::one("SELECT ROW_COUNT() as cnt")['cnt'] ?? 0; if ($affected) { DB::run("UPDATE users SET credit_balance = credit_balance + 5.00 WHERE id = :uid", [':uid' => $uid]); } } DB::run("INSERT INTO reviews (store_id, user_id, order_id, rating, title, body, is_approved, is_verified, helpful_count, created_at) VALUES (:sid, :uid, :oid, :r, :t, :b, 0, :iv, 0, NOW())", [':sid' => $storeId, ':uid' => $uid, ':oid' => ($hasCode['order_id'] ?? null), ':r' => $rating, ':t' => Crypt::encrypt($title, 'review'), ':b' => Crypt::encrypt($body, 'review'), ':iv' => $isVerified]); echo json_encode(['success' => true, 'verified' => $isVerified, 'credit_awarded' => ($isVerified ? 5.00 : 0), 'csrf' => Auth::regenerateCsrf()]); } catch (\Throwable $e) { error_log('[Review] submit: ' . $e->getMessage()); echo json_encode(['success' => false, 'error' => 'Could not submit review.', 'csrf' => Auth::regenerateCsrf()]); } exit; } if ($action !== 'vote') App::err('Unknown review action'); Security::enforceCSRF(); $reviewId = (int) ($in['review_id'] ?? 0); if ($reviewId <= 0) App::err('Invalid review ID'); $voteValue = (int) ($in['vote_value'] ?? 0); if ($voteValue !== 1 && $voteValue !== -1) App::err('Invalid vote value'); $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'; try { $existing = DB::one("SELECT id FROM review_votes WHERE review_id = :rid AND ip_address = :ip", [':rid' => $reviewId, ':ip' => $ip]); if ($existing) App::err('You have already voted.'); DB::run("INSERT INTO review_votes (review_id, ip_address, vote_score) VALUES (:rid, :ip, :vv)", [':rid' => $reviewId, ':ip' => $ip, ':vv' => $voteValue]); DB::run("UPDATE reviews SET helpful_count = helpful_count + :vv WHERE id = :rid", [':vv' => $voteValue, ':rid' => $reviewId]); App::ok(); } catch (\Throwable $e) { App::err('Internal server error', 500); } }
