<?php
require_once(__DIR__ . '/../../session.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (!isset($_SESSION['csrf_token']) || !isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    echo json_encode(['status' => 'error', 'message' => "Invalid CSRF Token!"]);
    exit();
  }

  $id = $_POST['id'] ?? null;
  $amount = isset($_POST['Amount']) && is_numeric($_POST['Amount']) ? floatval($_POST['Amount']) : 0;
  $type = $_POST['type'] ?? null;

  $stmt = $db->prepare("SELECT username FROM admin WHERE id = :admin_id LIMIT 1");
  $stmt->bindParam(':admin_id', $admin_id, PDO::PARAM_INT);
  $stmt->execute();
  $admin = $stmt->fetch(PDO::FETCH_ASSOC);

  $admin_username = $admin['username'];

  $stmt = $db->prepare("SELECT extplayer FROM user WHERE id = :id LIMIT 1");
  $stmt->bindParam(':id', $id, PDO::PARAM_INT);
  $stmt->execute();
  $user = $stmt->fetch(PDO::FETCH_ASSOC);

  if (!$user) {
    echo json_encode(['status' => 'error', 'message' => "User not found."]);
    exit();
  }

  $extplayer = $user['extplayer'];

  $stmt = $db->prepare("SELECT total_balance FROM balance WHERE user_id = :id LIMIT 1");
  $stmt->bindParam(':id', $id, PDO::PARAM_INT);
  $stmt->execute();
  $balance = $stmt->fetch(PDO::FETCH_ASSOC);

  if (!$balance) {
    echo json_encode(['status' => 'error', 'message' => "Balance not found."]);
    exit();
  }

  $activeBalance = floatval($balance['total_balance']);

  if ($type === 'add') {
      $newActiveBalance = $activeBalance + $amount;
      $stmt = $db->prepare("UPDATE balance SET total_balance = :total_balance, last_updated = :admin_username, updated_at = NOW() WHERE user_id = :id");
      $stmt->bindParam(':total_balance', $newActiveBalance, PDO::PARAM_STR);
      $stmt->bindParam(':admin_username', $admin_username, PDO::PARAM_STR);
      $stmt->bindParam(':id', $id, PDO::PARAM_INT);

      if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => "Saldo berhasil ditambahkan."]);
      } else {
        echo json_encode(['status' => 'error', 'message' => "Gagal memperbarui saldo!"]);
      }
  } elseif ($type === 'remove') {
    if ($activeBalance < $amount) {
      echo json_encode(['status' => 'error', 'message' => "Saldo tidak mencukupi!"]);
      exit();
    }

      $newActiveBalance = $activeBalance - $amount;
      $stmt = $db->prepare("UPDATE balance SET total_balance = :total_balance, last_updated = :admin_username, updated_at = NOW() WHERE user_id = :id");
      $stmt->bindParam(':total_balance', $newActiveBalance, PDO::PARAM_STR);
      $stmt->bindParam(':admin_username', $admin_username, PDO::PARAM_STR);
      $stmt->bindParam(':id', $id, PDO::PARAM_INT);

      if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => "Saldo berhasil dikurangi."]);
      } else {
        echo json_encode(['status' => 'error', 'message' => "Gagal mengurangi saldo!"]);
      }

  } else {
    echo json_encode(['status' => 'error', 'message' => "Aksi tidak valid!"]);
  }

  exit();
}

echo json_encode(['status' => 'error', 'message' => "Metode permintaan tidak valid."]);
