<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require '../config.php';

// echo '<pre>';
// print_r($_POST);
// exit;


// DB Connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Get POST data
$invoice_id = $_POST['invoice_id'] ?? null;
$uuid       = $_POST['uuid'] ?? null;
$hash       = $_POST['hash'] ?? null;
$amount     = $_POST['amount'] ?? null;
$currency   = $_POST['currency'] ?? 'USD';

$cardNumber   = str_replace(' ', '', $_POST['cardNumber'] ?? ''); // remove spaces
$expiryMonth = str_pad($_POST['expiryMonth'] ?? '', 2, '0', STR_PAD_LEFT);
$expiryYear  = substr($_POST['expiryYear'] ?? '', -2);
$ccexp = $expiryMonth . $expiryYear;


$cvv          = $_POST['cvv'] ?? null;

$customer_name    = $_POST['customer_name'] ?? null;
$customer_email   = $_POST['customer_email'] ?? null;
$customer_contact = $_POST['customer_contact'] ?? null;

$orderId = $invoice_id . '-' . uniqid();





// Fetch invoice
$invoice = $conn->query("SELECT * FROM invoices WHERE id = ".intval($invoice_id))->fetch_assoc();
if (!$invoice) die("Invoice not found");


// Fetch payment method
$paymentMethodId = intval($invoice['payment_method_id']);

$paymentMethod = $conn->query("
    SELECT epd_security_key 
    FROM payment_methods 
    WHERE id = $paymentMethodId
")->fetch_assoc();

if (!$paymentMethod) {
    die("Payment method not found");
}
$sandbox = true;

// sandbox secret key
$sandbox_secret_key = "eYT9DUR3Xd96peRgr8n967w3k3246tsX";


$secret_key = $sandbox 
    ? $sandbox_secret_key
    : $paymentMethod['epd_security_key'];



// Format expiry MMYY
$expiryMonth = str_pad($expiryMonth, 2, '0', STR_PAD_LEFT); // ensures 2 digits
$expiryYear = substr($expiryYear, -2); // last 2 digits of year
$ccexp = $expiryMonth . $expiryYear;

// Build API request
$vars = http_build_query([
    'type'         => 'sale',
    'security_key' => $secret_key,
    'amount'       => number_format($amount, 2, '.', ''),
    'ccnumber'     => $cardNumber,
    'ccexp'        => $ccexp,
    'cvv'          => $cvv,
    'orderid'      => $orderId,
    'first_name'   => $customer_name,
    'email'        => $customer_email,
    'phone'        => $customer_contact,
    'ipaddress'    => $_SERVER['REMOTE_ADDR'] ?? '',
    'currency'     => $currency
]);


$url = 'https://secure.easypaydirectgateway.com/api/transact.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);
if(curl_errno($ch)) {
    die("Curl error: " . curl_error($ch));
}
curl_close($ch);

// Parse URL-encoded response from EPD
parse_str($response, $resp);

// Debugging (optional)
// echo '<pre>'; print_r($resp); exit;

if (!$resp) {
    die("Invalid response from payment gateway");
}

// Check for success
if (isset($resp['response']) && $resp['response'] == '1') {

    $transactionId = $resp['transactionid'] ?? null;

    // Update invoice with status + transaction ID
    $stmt = $conn->prepare("
        UPDATE invoices 
        SET status = 'paid', easypay_direct_transaction_key = ?
        WHERE id = ?
    ");

    $stmt->bind_param("si", $transactionId, $invoice_id);
    $stmt->execute();

    header("Location: /invoice/secure/$uuid/$hash");
    exit;
} else {
    // Payment failed
    $errorMessage = $resp['responsetext'] ?? 'Unknown error';
    header("Location: /invoice/secure/$uuid/$hash?status=" . urlencode($errorMessage));
    exit;
}
