<?php
session_start();

if (!isset($_SESSION['user_id'])) {
  header("Location: ../../login.html");
  exit;
}

$pdo = new PDO("mysql:host=localhost;dbname=liongate;charset=utf8mb4", "root", "", [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

// Confirm admin
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :id LIMIT 1");
$stmt->execute([":id" => $_SESSION['user_id']]);
$me = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$me || (int)$me['is_admin'] !== 1) {
  http_response_code(403);
  exit("Access denied.");
}

$userId = (int)($_POST['user_id'] ?? 0);
$action = $_POST['action'] ?? '';
$amount = (float)($_POST['amount'] ?? 0);
$note   = trim($_POST['note'] ?? '');

if ($userId <= 0) exit("Invalid user.");
if (!in_array($action, ['credit','debit'], true)) exit("Invalid action.");
if ($amount <= 0) exit("Invalid amount.");

// Do update inside a DB transaction
$pdo->beginTransaction();

try {
  // Lock user row
  $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = :id FOR UPDATE");
  $stmt->execute([":id" => $userId]);
  $u = $stmt->fetch(PDO::FETCH_ASSOC);

  if (!$u) throw new Exception("User not found.");

  $balance = (float)$u['balance'];
  $newBal  = ($action === 'credit') ? ($balance + $amount) : ($balance - $amount);

  if ($newBal < 0) throw new Exception("Insufficient funds (would go negative).");

  // Update balance
  $stmt = $pdo->prepare("UPDATE users SET balance = :b WHERE id = :id");
  $stmt->execute([":b" => $newBal, ":id" => $userId]);

  // Log it
  $stmt = $pdo->prepare("
    INSERT INTO balance_logs (admin_id, user_id, action, amount, note)
    VALUES (:admin_id, :user_id, :action, :amount, :note)
  ");
  $stmt->execute([
    ":admin_id" => (int)$_SESSION['user_id'],
    ":user_id"  => $userId,
    ":action"   => $action,
    ":amount"   => $amount,
    ":note"     => $note
  ]);

  $pdo->commit();

  header("Location: ../../admin/fund_user.php?msg=Balance+updated+successfully");
  exit;

} catch (Exception $e) {
  $pdo->rollBack();
  exit("Failed: " . $e->getMessage());
}