<?php
session_start();
require_once "../include/db.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ref = mysqli_real_escape_string($conn, $_POST['ref']);
    $userId = $_SESSION['user_id'];

    // Handle File Upload
    $targetDir = "../uploads/proofs/";
    if (!file_exists($targetDir)) mkdir($targetDir, 0777, true);

    $fileName = $ref . "_" . time() . "_" . basename($_FILES["proof_img"]["name"]);
    $targetFilePath = $targetDir . $fileName;
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);

    $allowTypes = array('jpg', 'png', 'jpeg', 'pdf');
    if (in_array($fileType, $allowTypes)) {
        if (move_uploaded_file($_FILES["proof_img"]["tmp_name"], $targetFilePath)) {
            // Update Database
            $sql = "UPDATE transactions SET proof_img = '$fileName', status = 'pending' WHERE ref = '$ref' AND user_id = $userId";
            if (mysqli_query($conn, $sql)) {
                $_SESSION['success'] = "Receipt uploaded! Admin will verify your deposit shortly.";
                header("Location: ../dashboard.php");
            }
        } else {
            $_SESSION['error'] = "File upload failed.";
            header("Location: ../pay.php?ref=$ref");
        }
    } else {
        $_SESSION['error'] = "Only JPG, PNG, & PDF files are allowed.";
        header("Location: ../pay.php?ref=$ref");
    }
}