<?php
/* ============================================================
   إدارة الأصوات — للمسؤول فقط

   GET  api/votes.php?comp=ID    →  تفصيل الأصوات
   POST api/votes.php            →  {action:"reset", comp, cat?}
   ============================================================ */

declare(strict_types=1);
require __DIR__ . '/bootstrap.php';
require __DIR__ . '/helpers.php';
require __DIR__ . '/schema.php';

exp_start_session($CONFIG);
$user = exp_require_login();
$db = exp_db($CONFIG);

/* ---------- التفصيل ---------- */
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
  $comp = exp_id($_GET['comp'] ?? '');
  if ($comp === '') exp_fail('حدّد المسابقة');

  $st = $db->prepare(
    "SELECT c.uid, c.name, c.cat_id, COUNT(v.id) AS votes
       FROM exp_candidates c
       LEFT JOIN exp_votes v ON v.comp_id = c.comp_id AND v.cand_uid = c.uid
      WHERE c.comp_id = ?
      GROUP BY c.uid, c.name, c.cat_id
      ORDER BY c.cat_id, votes DESC"
  );
  $st->execute([$comp]);
  $rows = $st->fetchAll();

  $st2 = $db->prepare("SELECT COUNT(DISTINCT voter_key) n FROM exp_votes WHERE comp_id = ?");
  $st2->execute([$comp]);
  $voters = (int)$st2->fetch()['n'];

  $st3 = $db->prepare("SELECT MAX(created_at) t FROM exp_votes WHERE comp_id = ?");
  $st3->execute([$comp]);
  $last = $st3->fetch()['t'] ?? null;

  exp_json([
    'ok'         => true,
    'candidates' => array_map(fn($r) => [
      'uid'   => $r['uid'],
      'name'  => $r['name'],
      'cat'   => $r['cat_id'],
      'votes' => (int)$r['votes'],
    ], $rows),
    'voters'   => $voters,
    'total'    => array_sum(array_map(fn($r) => (int)$r['votes'], $rows)),
    'lastVote' => $last,
  ]);
}

/* ---------- تصفير الأصوات ---------- */
exp_require_post();
exp_check_origin();
exp_check_csrf();

$b = exp_body();
if (($b['action'] ?? '') !== 'reset') exp_fail('إجراء غير معروف');

$comp = exp_id($b['comp'] ?? '');
$cat  = exp_id($b['cat'] ?? '');
if ($comp === '') exp_fail('حدّد المسابقة');

try {
  if ($cat !== '') {
    $st = $db->prepare("DELETE FROM exp_votes WHERE comp_id = ? AND cat_id = ?");
    $st->execute([$comp, $cat]);
  } else {
    $st = $db->prepare("DELETE FROM exp_votes WHERE comp_id = ?");
    $st->execute([$comp]);
  }
  $n = $st->rowCount();
  exp_audit($db, $user, 'votes_reset', "المسابقة $comp" . ($cat !== '' ? " / الفئة $cat" : '') . " — حُذف $n صوت");
  exp_json(['ok' => true, 'deleted' => $n]);
} catch (Throwable $e) {
  error_log('votes.php: ' . $e->getMessage());
  exp_fail('تعذّر تصفير الأصوات', 500);
}
