<?php
session_start();
include '../../function/connect.php';

 $extplayer = $_SESSION['extplayer'] ?? null;

if (!$extplayer || !isset($_POST['submit'])) {
  header("Location: ../index.php?page=withdraw");
  exit;
}

 $bank    = $_POST['bank'] ?? '';
 $jumlah  = (int)($_POST['jumlah'] ?? 0);
 $tanggal = date('Y-m-d H:i:s');

/* ===== CEK SALDO ===== */
 $qSaldo = mysqli_query($koneksi, "
  SELECT active FROM tb_saldo WHERE id_user='$extplayer'
");
 $s = mysqli_fetch_assoc($qSaldo);
 $saldoAktif = (int)$s['active'];

if ($saldoAktif < $jumlah) {
  header("Location: ../index.php?page=withdraw&pesan=18");
  exit;
}

/* ===== INSERT TRANSAKSI ===== */
 $insert = mysqli_query($koneksi, "
  INSERT INTO tb_transaksi
  (gambar, tanggal, transaksi, total, dari_bank, metode, bonus, keterangan, status, id_user)
  VALUES
  ('', '$tanggal', 'Withdraw', '$jumlah', '$bank', '', '', '', 'Pending', '$extplayer')
");

/* ===== UPDATE SALDO ===== */
if ($insert) {
  mysqli_query($koneksi, "
    UPDATE tb_saldo
    SET active  = active - $jumlah,
        pending = pending + $jumlah
    WHERE id_user='$extplayer'
  ");

  header("Location: ../index.php?page=withdraw&pesan=20");
  exit;
}

header("Location: ../index.php?page=withdraw&pesan=35");
exit;