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

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

if (isset($_POST['simpan'])) {
    $user_id = $_SESSION['id'];
    $nominal = (float) $_POST['nominal'];

    if ($nominal < 1000) {
        setFlash('danger', 'Nominal minimal Rp 1.000');
        redirect('dashboard.php');
    }

    $file = $_FILES['bukti'];
    $allowed = ['jpg', 'jpeg', 'png'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed)) {
        setFlash('danger', 'Format file harus JPG/JPEG/PNG');
        redirect('dashboard.php');
    }

    if ($file['size'] > 2 * 1024 * 1024) {
        setFlash('danger', 'Ukuran file maksimal 2MB');
        redirect('dashboard.php');
    }

    $namaBaru = 'bukti_' . time() . '_' . rand(1000,9999) . '.' . $ext;
    move_uploaded_file($file['tmp_name'], '../uploads/' . $namaBaru);

    $stmt = mysqli_prepare($conn, "INSERT INTO transactions (user_id, nominal, bukti_transfer, status) VALUES (?, ?, ?, 'pending')");
    mysqli_stmt_bind_param($stmt, "ids", $user_id, $nominal, $namaBaru);
    mysqli_stmt_execute($stmt);

    setFlash('success', 'Setoran berhasil diajukan');
    redirect('dashboard.php');
}
?>