<?php
session_start();
require_once(__DIR__ . "/../config/db.php");
require_once(__DIR__."/../session.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("CSRF token tidak valid");
    }

    $amount = $_POST['Amount'];
    $from = $_POST['FromAccount'];
    $to = $_POST['ToAccount'];
    $TransactionReceipt = NULL;
    $type = 'deposit';

    $checkPending = "SELECT COUNT(*) FROM transaction WHERE user_id = :user_id AND type = :type AND Status = 0";
    $stmt = $db->prepare($checkPending);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->bindParam(':type', $type);
    $stmt->execute();
    if ($stmt->fetchColumn() > 0) {
        $_SESSION['error'] = "Kamu Masih Memiliki Transaksi Tertunda";
        header("Location: /");
        exit();
    }

    if ($amount < 50000) {
        $_SESSION['error'] = "Minimal Deposit Rp. 50,000";
        header("Location: /");
        exit();
    }

    $uploadDir = '../Images/TransactionReceipt/';
    $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
    $maxFileSize = 2 * 1024 * 1024;

    if (isset($_FILES['TransactionReceipt']) && $_FILES['TransactionReceipt']['error'] === UPLOAD_ERR_OK) {
        if (!in_array($_FILES['TransactionReceipt']['type'], $allowedTypes) || $_FILES['TransactionReceipt']['size'] > $maxFileSize) {
            $_SESSION['error'] = "File tidak valid";
            header("Location: /");
            exit();
        }

        $filename = uniqid() . '_' . $_FILES['TransactionReceipt']['name'];
        $targetPath = $uploadDir . $filename;

        if (!move_uploaded_file($_FILES['TransactionReceipt']['tmp_name'], $targetPath)) {
            $_SESSION['error'] = "Upload failed";
            header("Location: /");
            exit();
        }

        $TransactionReceipt = $targetPath;
    }

    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    do {
        $trxid = '';
        for ($i = 0; $i < 8; $i++) {
            $trxid .= $characters[random_int(0, strlen($characters) - 1)];
        }
        $checkTransaction = "SELECT COUNT(*) FROM transaction WHERE trxid = :trxid";
        $stmt = $db->prepare($checkTransaction);
        $stmt->bindParam(':trxid', $trxid);
        $stmt->execute();
    } while ($stmt->fetchColumn());

    $insertDeposit = "INSERT INTO transaction (user_id, trxid, type, Amount, FromAccount, ToAccount, TransactionReceipt, created_at, updated_at) VALUES (:user_id, :trxid, :type, :Amount, :FromAccount, :ToAccount, :TransactionReceipt, NOW(), NOW())";
    $stmt = $db->prepare($insertDeposit);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->bindParam(':trxid', $trxid);
    $stmt->bindParam(':type', $type);
    $stmt->bindParam(':Amount', $amount);
    $stmt->bindParam(':FromAccount', $from);
    $stmt->bindParam(':ToAccount', $to);
    $stmt->bindParam(':TransactionReceipt', $TransactionReceipt);

    if ($stmt->execute()) {
        $_SESSION['message'] = "Permintaan Deposit Berhasil Dikirim";
        header("Location: /");
    } else {
        $_SESSION['error'] = "Transaction failed";
        header("Location: /");
    }

    exit();
}
?>