<?php
//process_payment.php
session_start();

require_once('config.php');

define('UPLOAD_DIR', 'uploads/payment_proofs/');
define('MAX_FILE_SIZE', 5 * 1024 * 1024); // 5MB

function handle_upload(array $file, string $method) {
    global $pdo;

    if ($file['error'] !== UPLOAD_ERR_OK) {
        return false;
    }

    if ($file['size'] > MAX_FILE_SIZE) {
        return false;
    }

    
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    
    $allowed_mimes = ['image/jpeg', 'image/png', 'application/pdf'];
    if ($method === 'gc_front' || $method === 'gc_back') {
        
        $allowed_mimes = ['image/jpeg', 'image/png'];
    }

    if (!in_array($mime_type, $allowed_mimes)) {
        return false;
    }

    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = $method . '_' . md5($file['name']) . '_' . uniqid() . '.' . $ext;
    $destination = UPLOAD_DIR . $filename;

    if (move_uploaded_file($file['tmp_name'], $destination)) {
        return $destination;
    }

    return false;
}


if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['payment_method'])) {
    $_SESSION['alert'] = [
        'type' => 'error',
        'title' => 'Invalid Request',
        'text' => 'The payment form was submitted incorrectly.'
    ];
    header('Location: index.php');
    exit;
}

$method = $_POST['payment_method'];

try {
    // 1. EXTRACT SHIPMENT DETAILS
    $shipment_id = filter_var($_POST['shipment_id'] ?? null, FILTER_VALIDATE_INT);
    $tracking_number = filter_var($_POST['tracking_number'] ?? null, FILTER_SANITIZE_SPECIAL_CHARS);
    
    if (!$shipment_id || empty($tracking_number)) {
        throw new Exception('Missing or invalid shipment identification fields.');
    }
    
    $amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);
    if ($amount === false || $amount <= 0) {
        throw new Exception('Invalid payment amount specified.');
    }

    // ===============================================
    //           *** DUPLICATE SUBMISSION CHECK ***
    // Checks if a proof is already waiting for review or approved (NOT Declined)
    // ===============================================
    $check_query = "SELECT COUNT(*) FROM payment_proofs 
                    WHERE shipment_id = :shipment_id 
                    AND proof_status IN ('Pending Review', 'Approved')";
    $stmt = $pdo->prepare($check_query);
    $stmt->bindParam(':shipment_id', $shipment_id);
    $stmt->execute();
    $proof_count = $stmt->fetchColumn();

    if ($proof_count > 0) {
        // Blocked because a non-declined proof already exists.
        $_SESSION['alert'] = [
            'type' => 'warning',
            'title' => 'Submission Pending 🔒',
            'text' => 'A payment proof for this shipment is already being reviewed or has been approved. Please wait for an update.'
        ];
        header('Location: index.php?tracking_number=' . urlencode($tracking_number));
        exit; // Stop script execution
    }
    
    // ===============================================
    //        *** END DUPLICATE CHECK ***
    // ===============================================

    // 2. INSERT INTO payment_proofs TABLE (Updated to include proof_status)
    $insert_query = "
        INSERT INTO payment_proofs
        (shipment_id, tracking_number, payment_method, amount, proof_status,
         bank_proof_path, crypto_currency, crypto_amount_raw, crypto_proof_path,
         giftcard_value_usd, giftcard_proof_front_path, giftcard_proof_back_path)
        VALUES
        (:shipment_id, :tracking_number, :method, :amount, :proof_status,
         :bank_path, :crypto_curr, :crypto_raw, :crypto_path,
         :gc_value, :gc_front, :gc_back)
    ";

    $params = [
        ':shipment_id' => $shipment_id,
        ':tracking_number' => $tracking_number,
        ':method' => $method,
        ':amount' => $amount,
        ':proof_status' => 'Pending Review', // Set initial status
        ':bank_path' => null,
        ':crypto_curr' => null,
        ':crypto_raw' => null,
        ':crypto_path' => null,
        ':gc_value' => null,
        ':gc_front' => null,
        ':gc_back' => null
    ];

    switch ($method) {
        case 'bank':
            if (empty($_FILES['payment_proof']['name'])) {
                throw new Exception('Bank proof file is required.');
            }
            $bank_path = handle_upload($_FILES['payment_proof'], 'bank');
            if (!$bank_path) {
                throw new Exception('Failed to process bank proof file.');
            }
            $params[':bank_path'] = $bank_path;
            break;

        case 'crypto':
            if (empty($_FILES['payment_proof']['name'])) {
                throw new Exception('Crypto transaction proof is required.');
            }
            $crypto_path = handle_upload($_FILES['payment_proof'], 'crypto');
            $currency = filter_var($_POST['currency'], FILTER_SANITIZE_SPECIAL_CHARS);
            $amount_raw = filter_var($_POST['amount'], FILTER_SANITIZE_SPECIAL_CHARS);

            if (!$crypto_path) {
                throw new Exception('Failed to process crypto proof file.');
            }
            if (empty($currency) || !in_array($currency, ['btc', 'eth', 'ltc', 'usdt'])) {
                throw new Exception('Invalid cryptocurrency selected.');
            }

            $params[':crypto_curr'] = $currency;
            $params[':crypto_raw'] = $amount_raw;
            $params[':crypto_path'] = $crypto_path;
            break;

        case 'giftcard':
            if (empty($_FILES['proof_front']['name']) || empty($_FILES['proof_back']['name'])) {
                throw new Exception('Both front and back gift card proofs are required.');
            }
            $front_path = handle_upload($_FILES['proof_front'], 'gc_front');
            $back_path = handle_upload($_FILES['proof_back'], 'gc_back');

            if (!$front_path || !$back_path) {
                throw new Exception('Failed to process one or both gift card proofs.');
            }

            $params[':gc_value'] = $amount;
            $params[':gc_front'] = $front_path;
            $params[':gc_back'] = $back_path;
            break;

        default:
            throw new Exception('Invalid payment method selected.');
    }
    
    // Execute INSERT for payment_proofs
    $stmt = $pdo->prepare($insert_query);
    $stmt->execute($params);

    $_SESSION['alert'] = [
        'type' => 'success',
        'title' => 'Proof Submitted! 🎉',
        'text' => 'Your payment proof has been successfully submitted and is pending administrative review.'
    ];
    
    // Redirect back to the tracking page for the specific shipment
    header('Location: index.php?tracking_number=' . urlencode($tracking_number));
    exit;

} catch (Exception $e) {
    error_log("Payment Processing Error (" . $method . "): " . $e->getMessage());
    $_SESSION['alert'] = [
        'type' => 'error',
        'title' => 'Submission Failed 😢',
        'text' => 'Error: ' . $e->getMessage()
    ];
    header('Location: index.php');
    exit;
}
?>