<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }
$ctx = Kernel::handle(['auth' => 'optional']);
$u = $ctx['user'];
$uid = (int)($u['id'] ?? 0);
$b   = json_decode(file_get_contents('php://input'), true) ?? [];
$sid = (int)($b['suggestion_id'] ?? 0);
if (!$sid) { http_response_code(400); die(json_encode(['error'=>'suggestion_id_required'])); }
$sessionId = session_id() ?: hash('sha256', $_SERVER['REMOTE_ADDR'] ?? '');
try {
    db()->prepare("INSERT INTO suggestion_votes (suggestion_id,user_id,session_id) VALUES (?,?,?)")
       ->execute([$sid, $uid ?: null, $sessionId]);
    $upd = db()->prepare("UPDATE user_suggestions SET votes_count=votes_count+1 WHERE id=?");
    $upd->execute([$sid]);
    $sv = db()->prepare("SELECT votes_count FROM user_suggestions WHERE id=? LIMIT 1");
    $sv->execute([$sid]);
    $votes = (int)($sv->fetchColumn() ?? 0);
    echo json_encode(['ok'=>true,'votes'=>$votes]);
} catch (Throwable $e) {
    http_response_code(409);
    echo json_encode(['error'=>'already_voted','message'=>'صوَّت مسبقاً على هذا الاقتراح']);
}
