<?php
include '../config/koneksi.php';
include '../helpers/functions.php';

if (!isLogin() || !isAdmin()) redirect('../auth/login.php');

$id = (int) $_GET['id'];
$wd = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM withdrawals WHERE id=$id"));

if ($wd && $wd['status'] == 'pending') {
    $user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT saldo FROM users WHERE id={$wd['user_id']}"));

    if ($user['saldo'] >= $wd['nominal']) {
        mysqli_begin_transaction($conn);

        try {
            mysqli_query($conn, "UPDATE withdrawals SET status='confirmed', confirmed_at=NOW(), catatan_admin='Penarikan dikonfirmasi admin' WHERE id=$id");
            mysqli_query($conn, "UPDATE users SET saldo = saldo - {$wd['nominal']} WHERE id={$wd['user_id']}");
            mysqli_commit($conn);
            setFlash('success', 'Penarikan berhasil dikonfirmasi');
        } catch (Exception $e) {
            mysqli_rollback($conn);
            setFlash('danger', 'Gagal konfirmasi penarikan');
        }
    } else {
        setFlash('danger', 'Saldo user tidak mencukupi saat konfirmasi');
    }
}

redirect('withdrawals.php');
?>