<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

$conn = require __DIR__ . '/../../app/config/database.php';
require_login();
csrf_verify();

$admin = current_user();
$ref = trim($_POST['ref'] ?? '');
$do  = trim($_POST['do'] ?? '');

if (!$ref || !in_array($do, ['approve','reject'], true)) {
  flash('err','Invalid request');
  redirect('crypto_multisig_review.php');
}

try {
  $conn->begin_transaction();

  $st = $conn->prepare("SELECT * FROM crypto_multisig WHERE ref=? FOR UPDATE");
  $st->bind_param("s", $ref);
  $st->execute();
  $m = $st->get_result()->fetch_assoc();

  if (!$m || $m['status'] !== 'pending') {
    $conn->rollback();
    throw new Exception('Not pending.');
  }

  // insert approval (unique per admin)
  $msId = (int)$m['id'];
  $decision = $do;
  $note = null;

  $st2 = $conn->prepare("
    INSERT INTO crypto_multisig_approvals (multisig_id, approver_id, decision, note)
    VALUES (?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE decision=VALUES(decision), note=VALUES(note)
  ");
  $st2->bind_param("iiss", $msId, $admin['id'], $decision, $note);
  $st2->execute();

  // count approvals/rejections
  $st3 = $conn->prepare("
    SELECT
      SUM(CASE WHEN decision='approve' THEN 1 ELSE 0 END) AS a,
      SUM(CASE WHEN decision='reject' THEN 1 ELSE 0 END) AS r
    FROM crypto_multisig_approvals
    WHERE multisig_id=?
  ");
  $st3->bind_param("i", $msId);
  $st3->execute();
  $c = $st3->get_result()->fetch_assoc();
  $appr = (int)($c['a'] ?? 0);
  $rej  = (int)($c['r'] ?? 0);

  if ($rej >= 1) {
    $up = $conn->prepare("UPDATE crypto_multisig SET status='rejected' WHERE id=?");
    $up->bind_param("i", $msId);
    $up->execute();
    $conn->commit();
    flash('msg','Rejected.');
    redirect('crypto_multisig_review.php');
  }

  if ($appr >= (int)$m['approvals_needed']) {
    $up = $conn->prepare("UPDATE crypto_multisig SET status='approved' WHERE id=?");
    $up->bind_param("i", $msId);
    $up->execute();
    $conn->commit();
    flash('msg','Approved (threshold met).');
    redirect('crypto_multisig_review.php');
  }

  $conn->commit();
  flash('msg','Recorded.');
  redirect('crypto_multisig_review.php');

} catch(Throwable $e) {
  $conn->rollback();
  flash('err',$e->getMessage());
  redirect('crypto_multisig_review.php');
}
