<?php
$manual_topup_message = '';
if (isset($conn) && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['manual_top_up'])) {
    $user_id_for_topup = $_SESSION['user_id'] ?? 0;
    $payment_method_id = intval($_POST['payment_method_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    $reference_number = trim(strip_tags($_POST['reference_number'] ?? ''));
    $proof_url = '';
    
    if ($amount <= 0 || empty($reference_number) || $payment_method_id <= 0) {
        $manual_topup_message = '<div class="alert alert-warning mt-3">Please fill in all fields.</div>';
    } elseif (!isset($_FILES['proof_of_payment']) || $_FILES['proof_of_payment']['error'] != 0) {
        $manual_topup_message = '<div class="alert alert-danger mt-3">Please choose a valid image file.</div>';
    } else {
        $target_dir = "../uploads/proofs/";
        if (!is_dir($target_dir)) { @mkdir($target_dir, 0755, true); }

        if (empty($manual_topup_message) && !is_writable($target_dir)) {
            $manual_topup_message = '<div class="alert alert-danger mt-3">Error: Server directory is not writable.</div>';
        }

        if (empty($manual_topup_message)) {
            $safe_filename = preg_replace("/[^a-zA-Z0-9-_\.]/", "", basename($_FILES["proof_of_payment"]["name"]));
            $target_file = $target_dir . "proof-" . $user_id_for_topup . "-" . uniqid() . "-" . $safe_filename;
            if (move_uploaded_file($_FILES["proof_of_payment"]["tmp_name"], $target_file)) {
                $proof_url = str_replace('../', '', $target_file);
                $stmt_method = $conn->prepare("SELECT method_name FROM payment_methods WHERE id=?");
                $stmt_method->bind_param("i", $payment_method_id);
                $stmt_method->execute();
                $payment_method_name = $stmt_method->get_result()->fetch_assoc()['method_name'];

                $stmt = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, payment_method, reference_number, proof_of_payment_url, status) VALUES (?, 'Top-up', ?, ?, ?, ?, 'Pending')");
                $stmt->bind_param("idsss", $user_id_for_topup, $amount, $payment_method_name, $reference_number, $proof_url);
                if ($stmt->execute()) {
                    $manual_topup_message = '<div class="alert alert-success mt-3">Your top-up request has been submitted and is awaiting review.</div>';
                }
            } else {
                $manual_topup_message = '<div class="alert alert-danger mt-3">Sorry, there was an error saving your uploaded file.</div>';
            }
        }
    }
}
?>

<?php if (!empty($manual_topup_message)) { echo $manual_topup_message; } ?>
<form method="POST" enctype="multipart/form-data" action="top-up.php">
    <input type="hidden" name="manual_top_up" value="1">
    <div class="mb-3">
        <label class="form-label">1. Payment Method Used</label>
        <select name="payment_method_id" id="paymentMethodSelect" class="form-select" required>
            <option value="" disabled selected>-- Select a Method to see details --</option>
            <?php if (isset($conn)) { $pm_result = $conn->query("SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY method_name"); if ($pm_result) { while($pm = $pm_result->fetch_assoc()): ?><option value="<?php echo $pm['id']; ?>"><?php echo htmlspecialchars($pm['method_name']); ?></option><?php endwhile; } } ?>
        </select>
    </div>
    <div class="mb-3"><label class="form-label">2. Amount Sent (PHP)</label><input type="number" step="0.01" name="amount" class="form-control" required></div>
    <div class="mb-3"><label class="form-label">3. Reference Number</label><input type="text" name="reference_number" class="form-control" required></div>
    <div class="mb-3"><label class="form-label">4. Proof of Payment (Screenshot)</label><input type="file" name="proof_of_payment" class="form-control" required accept="image/*"></div>
    <button type="submit" class="btn btn-primary">Submit Request</button>
</form>
