<?php
session_start();
include 'config.php';

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

$user_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';

// RATE KURS (Hardcoded untuk kestabilan sistem)
// Idealnya diambil dari database settings
$RATE_USD_IDR = 16000; 

// ============================================================
// 1. FITUR TRANSFER SESAMA MEMBER (SEND)
// ============================================================
if ($action == 'send') {
    $target_username = $conn->real_escape_string($_POST['username']);
    $amount = intval($_POST['amount']);

    // Validasi Input
    if ($amount <= 0) {
        $_SESSION['flash'] = "Nominal transfer tidak valid.";
        header("Location: dashboard.php"); exit();
    }

    // Cek Saldo Pengirim
    $sender = $conn->query("SELECT balance_idr FROM users WHERE id = $user_id")->fetch_assoc();
    if ($sender['balance_idr'] < $amount) {
        $_SESSION['flash'] = "Saldo IDR Anda tidak mencukupi!";
        header("Location: dashboard.php"); exit();
    }

    // Cek Penerima
    $check_target = $conn->query("SELECT id, username FROM users WHERE username = '$target_username'");
    if ($check_target->num_rows == 0) {
        $_SESSION['flash'] = "Username penerima tidak ditemukan.";
        header("Location: dashboard.php"); exit();
    }
    $recipient = $check_target->fetch_assoc();
    
    // Cegah transfer ke diri sendiri
    if ($recipient['id'] == $user_id) {
        $_SESSION['flash'] = "Tidak bisa transfer ke diri sendiri.";
        header("Location: dashboard.php"); exit();
    }

    // MULAI TRANSAKSI DATABASE (Atomicity)
    $conn->begin_transaction();

    try {
        // 1. Kurangi Saldo Pengirim
        $conn->query("UPDATE users SET balance_idr = balance_idr - $amount WHERE id = $user_id");
        
        // 2. Tambah Saldo Penerima
        $conn->query("UPDATE users SET balance_idr = balance_idr + $amount WHERE id = " . $recipient['id']);

        // 3. Catat History Pengirim
        $desc_out = "Transfer ke " . $recipient['username'];
        $conn->query("INSERT INTO transactions (user_id, type, amount, status, description) VALUES ($user_id, 'transfer_out', $amount, 'success', '$desc_out')");

        // 4. Catat History Penerima
        // Ambil nama pengirim untuk log penerima
        $my_username = $conn->query("SELECT username FROM users WHERE id = $user_id")->fetch_assoc()['username'];
        $desc_in = "Terima dari " . $my_username;
        $conn->query("INSERT INTO transactions (user_id, type, amount, status, description) VALUES (" . $recipient['id'] . ", 'transfer_in', $amount, 'success', '$desc_in')");

        $conn->commit();
        $_SESSION['flash'] = "Berhasil transfer Rp " . number_format($amount) . " ke " . $target_username;
    
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['flash'] = "Gagal memproses transfer. Coba lagi.";
    }

    header("Location: dashboard.php");
    exit();
}

// ============================================================
// 2. FITUR TOP UP (DEPOSIT)
// ============================================================
if ($action == 'topup') {
    $amount = intval($_POST['amount']);
    $method = $conn->real_escape_string($_POST['method']);

    if ($amount < 10000) {
        $_SESSION['flash'] = "Minimal Top Up Rp 10.000";
        header("Location: dashboard.php"); exit();
    }

    $desc = "Top Up via " . $method;
    
    // Status Pending (Menunggu Admin Approve)
    $sql = "INSERT INTO transactions (user_id, type, amount, status, description) 
            VALUES ($user_id, 'topup', $amount, 'pending', '$desc')";

    if ($conn->query($sql)) {
        $_SESSION['flash'] = "Tagihan Top Up berhasil dibuat. Silakan lakukan pembayaran.";
    } else {
        $_SESSION['flash'] = "Gagal membuat tagihan.";
    }
    header("Location: dashboard.php");
    exit();
}

// ============================================================
// 3. FITUR WITHDRAW (PENARIKAN)
// ============================================================
if ($action == 'withdraw') {
    $amount = intval($_POST['amount']);
    $bank_details = $conn->real_escape_string($_POST['bank_details']); // format: "BCA - 123456"

    if ($amount < 50000) {
        $_SESSION['flash'] = "Minimal Withdraw Rp 50.000";
        header("Location: dashboard.php"); exit();
    }

    // Cek Saldo
    $user = $conn->query("SELECT balance_idr FROM users WHERE id = $user_id")->fetch_assoc();
    if ($user['balance_idr'] < $amount) {
        $_SESSION['flash'] = "Saldo tidak mencukupi untuk penarikan.";
        header("Location: dashboard.php"); exit();
    }

    // PROSES: Potong Saldo DULUAN (agar tidak withdraw double)
    $conn->begin_transaction();
    try {
        // 1. Potong Saldo
        $conn->query("UPDATE users SET balance_idr = balance_idr - $amount WHERE id = $user_id");

        // 2. Catat Transaksi (Pending)
        $desc = "Withdraw ke " . $bank_details;
        $conn->query("INSERT INTO transactions (user_id, type, amount, status, description) 
                      VALUES ($user_id, 'withdraw', $amount, 'pending', '$desc')");

        $conn->commit();
        $_SESSION['flash'] = "Permintaan Withdraw berhasil dikirim. Menunggu persetujuan Admin.";

    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['flash'] = "Gagal memproses withdraw.";
    }

    header("Location: dashboard.php");
    exit();
}

// ============================================================
// 4. FITUR SWAP CURRENCY (IDR <-> USD)
// ============================================================
if ($action == 'swap') {
    $from = $_POST['from_currency']; // IDR atau USD
    $amount_input = floatval($_POST['amount']);

    if ($amount_input <= 0) {
        $_SESSION['flash'] = "Jumlah swap tidak valid.";
        header("Location: dashboard.php"); exit();
    }

    $user = $conn->query("SELECT balance_idr, balance_usd FROM users WHERE id = $user_id")->fetch_assoc();

    $conn->begin_transaction();
    try {
        if ($from == 'IDR') {
            // IDR to USD
            if ($user['balance_idr'] < $amount_input) throw new Exception("Saldo IDR Kurang");
            
            $usd_got = $amount_input / $RATE_USD_IDR;
            
            $conn->query("UPDATE users SET balance_idr = balance_idr - $amount_input, balance_usd = balance_usd + $usd_got WHERE id = $user_id");
            $desc = "Swap IDR " . number_format($amount_input) . " to USD " . number_format($usd_got, 2);
            
        } else {
            // USD to IDR
            if ($user['balance_usd'] < $amount_input) throw new Exception("Saldo USD Kurang");
            
            $idr_got = $amount_input * $RATE_USD_IDR;
            
            $conn->query("UPDATE users SET balance_usd = balance_usd - $amount_input, balance_idr = balance_idr + $idr_got WHERE id = $user_id");
            $desc = "Swap USD " . number_format($amount_input, 2) . " to IDR " . number_format($idr_got);
        }

        // Catat Log
        $conn->query("INSERT INTO transactions (user_id, type, amount, status, description) VALUES ($user_id, 'swap', $amount_input, 'success', '$desc')");

        $conn->commit();
        $_SESSION['flash'] = "Swap Berhasil!";

    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['flash'] = "Swap Gagal: " . $e->getMessage();
    }

    header("Location: dashboard.php");
    exit();
}

// ============================================================
// 5. FITUR BELI PAKET STOKIS (NEW)
// ============================================================
if ($action == 'buy_stokis') {
    $amount = intval($_POST['amount']);
    $pkg_name = $conn->real_escape_string($_POST['package_name']);
    $duration = $conn->real_escape_string($_POST['duration']);
    $method = $conn->real_escape_string($_POST['payment_method']);
    
    // Upload Bukti Transfer
    $proof_name = null;
    if (isset($_FILES['proof']) && $_FILES['proof']['error'] == 0) {
        $target_dir = "uploads/";
        if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
        
        $extension = pathinfo($_FILES['proof']['name'], PATHINFO_EXTENSION);
        $proof_name = "stokis_" . time() . "_" . $user_id . "." . $extension;
        
        move_uploaded_file($_FILES['proof']['tmp_name'], $target_dir . $proof_name);
    }

    $desc = "Pembelian Paket Stokis: $pkg_name ($duration Bulan)";
    
    // Insert Pending Transaction
    $sql = "INSERT INTO transactions (user_id, type, amount, status, description, proof_image) 
            VALUES ($user_id, 'buy_stokis', $amount, 'pending', '$desc', '$proof_name')";
    
    if ($conn->query($sql)) {
        $_SESSION['flash'] = "Request Paket Stokis dikirim. Menunggu Approval Admin.";
        header("Location: stokis.php"); 
    } else {
        $_SESSION['flash'] = "Gagal memproses data.";
        header("Location: stokis.php");
    }
    exit();
}

// ============================================================
// 6. FITUR BELI PAKET CROWD (NEW)
// ============================================================
if ($action == 'buy_crowd') {
    $amount = intval($_POST['amount']);
    $pkg_name = $conn->real_escape_string($_POST['package_name']);
    $duration = $conn->real_escape_string($_POST['duration']); // Meski tidak diminta di UI crowd, jaga2 jika ada
    $method = $conn->real_escape_string($_POST['payment_method']);
    
    // Upload Bukti
    $proof_name = null;
    if (isset($_FILES['proof']) && $_FILES['proof']['error'] == 0) {
        $target_dir = "uploads/";
        if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
        
        $extension = pathinfo($_FILES['proof']['name'], PATHINFO_EXTENSION);
        $proof_name = "crowd_" . time() . "_" . $user_id . "." . $extension;
        
        move_uploaded_file($_FILES['proof']['tmp_name'], $target_dir . $proof_name);
    }

    $desc = "Pembelian Crowd: $pkg_name";
    if($duration) $desc .= " ($duration Bulan)";

    $sql = "INSERT INTO transactions (user_id, type, amount, status, description, proof_image) 
            VALUES ($user_id, 'buy_crowd', $amount, 'pending', '$desc', '$proof_name')";
    
    if ($conn->query($sql)) {
        $_SESSION['flash'] = "Request Crowdfunding dikirim. Menunggu Approval Admin.";
        header("Location: crowd.php");
    } else {
        $_SESSION['flash'] = "Gagal memproses data.";
        header("Location: crowd.php");
    }
    exit();
}

// ============================================================
// 7. FITUR BELI PAKET CRYPTO (NEW)
// ============================================================
if ($action == 'buy_crypto') {
    $amount = intval($_POST['amount']);
    $pkg_name = $conn->real_escape_string($_POST['package_name']);
    $cat = $conn->real_escape_string($_POST['category']); // staking, mining, earning
    $method = $conn->real_escape_string($_POST['payment_method']);
    
    // BRANCH A: POTONG SALDO
    if ($method == 'Potong Saldo') {
        // Cek Saldo
        $cek = $conn->query("SELECT balance_idr FROM users WHERE id = $user_id")->fetch_assoc();
        if ($cek['balance_idr'] < $amount) {
            $_SESSION['flash'] = "Saldo IDR Anda tidak mencukupi untuk pembelian ini.";
            header("Location: crypto.php"); exit();
        }
        
        // Transaksi Potong Saldo
        $conn->begin_transaction();
        try {
            $conn->query("UPDATE users SET balance_idr = balance_idr - $amount WHERE id = $user_id");
            
            $desc = "Beli Crypto ($cat): $pkg_name (Potong Saldo)";
            
            // Masuk status 'pending' agar admin mengaktifkan 'mesin mining/staking' nya secara manual/sistem
            // Jika ingin otomatis aktif, ubah status ke 'success'
            $conn->query("INSERT INTO transactions (user_id, type, amount, status, description) 
                          VALUES ($user_id, 'buy_crypto', $amount, 'pending', '$desc')");
            
            $conn->commit();
            $_SESSION['flash'] = "Pembelian Crypto Berhasil (Menunggu Aktivasi Admin).";
            
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['flash'] = "Gagal memproses pembelian.";
        }
    } 
    // BRANCH B: TRANSFER MANUAL
    else {
        // Upload Bukti
        $proof_name = null;
        if (isset($_FILES['proof']) && $_FILES['proof']['error'] == 0) {
            $target_dir = "uploads/";
            if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
            
            $extension = pathinfo($_FILES['proof']['name'], PATHINFO_EXTENSION);
            $proof_name = "crypto_" . time() . "_" . $user_id . "." . $extension;
            
            move_uploaded_file($_FILES['proof']['tmp_name'], $target_dir . $proof_name);
        }

        $desc = "Beli Crypto ($cat): $pkg_name via $method";
        $sql = "INSERT INTO transactions (user_id, type, amount, status, description, proof_image) 
                VALUES ($user_id, 'buy_crypto', $amount, 'pending', '$desc', '$proof_name')";
        
        $conn->query($sql);
        $_SESSION['flash'] = "Bukti transfer Crypto dikirim. Menunggu verifikasi Admin.";
    }
    
    header("Location: crypto.php");
    exit();
}

// Jika Action Tidak Dikenal
header("Location: dashboard.php");
exit();
?>