<?php
require 'config.php';
require 'vendor/autoload.php';

use Square\SquareClient;
use Square\Exceptions\ApiException;
use Square\Models\Money;
use Square\Models\CreatePaymentRequest;

// Database connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die("DB Connection failed: " . $conn->connect_error);
}

// Validate input
$required = ['nonce', 'invoice_id', 'uuid', 'hash', 'amount'];
foreach ($required as $field) {
    if (empty($_POST[$field])) die("Missing required field: $field");
}

$invoiceId = (int)$_POST['invoice_id'];
$uuid = $conn->real_escape_string($_POST['uuid']);
$clientHash = $conn->real_escape_string($_POST['hash']);
$amount = (float)$_POST['amount'];
$nonce = $conn->real_escape_string($_POST['nonce']);

// Verify invoice

// ---------------------------------------
// Load Payment Gateway Dynamic Settings
// ---------------------------------------
$pmStmt = $conn->prepare("
    SELECT payment_method_id 
    FROM invoices 
    WHERE id = ?
");
$pmStmt->bind_param("i", $invoiceId);
$pmStmt->execute();
$invResult = $pmStmt->get_result();
$invData = $invResult->fetch_assoc();
$pmStmt->close();

$pmId = $invData['payment_method_id'] ?? null;

// Default fallback IDs
$defaultIds = [
    'square' => 1,
    'stripe' => 2,
    'paypal' => 3
];

// If payment_method_id missing, fallback to default
if (empty($pmId)) {
    $pmId = $defaultIds['square']; 
}

// Fetch actual gateway keys
$gwStmt = $conn->prepare("SELECT * FROM payment_methods WHERE id = ? AND status = 1");
$gwStmt->bind_param("i", $pmId);
$gwStmt->execute();
$gwRes = $gwStmt->get_result();
$gateway = $gwRes->fetch_assoc();
$gwStmt->close();

// Set constants
define('SQUARE_ACCESS_TOKEN', $gateway['square_access_token'] ?? '');
define('SQUARE_LOCATION_ID', $gateway['square_location_id'] ?? '');
define('SQUARE_APPLICATION_ID', $gateway['square_application_id'] ?? '');



$stmt = $conn->prepare("SELECT salt,currency FROM invoices WHERE id = ? AND uuid = ?");
$stmt->bind_param("is", $invoiceId, $uuid);
$stmt->execute();
$result = $stmt->get_result();
$invoice = $result->fetch_assoc();
$stmt->close();

if (!$invoice || !hash_equals(generateInvoiceHash($invoiceId, $invoice['salt']), $clientHash)) {
    die("Invalid payment request");
}

// Process payment
$client = new SquareClient([
    'accessToken' => SQUARE_ACCESS_TOKEN,
    'environment' => 'production'
]);

try {
    // $amountMoney = (new Money())->setAmount((int)($amount * 100))->setCurrency('USD');
    $amountMoney = new Money();
    $amountMoney->setAmount((int)($amount * 100)); // in cents
    $amountMoney->setCurrency($invoice['currency']);

    // $paymentRequest = (new CreatePaymentRequest($nonce, uniqid()))->setAmountMoney($amountMoney);

    // Use required constructor
    $paymentRequest = new CreatePaymentRequest(
        $nonce,
        uniqid()
    );

    $paymentRequest->setAmountMoney($amountMoney);

    $response = $client->getPaymentsApi()->createPayment($paymentRequest);

    if ($response->isSuccess()) {
        $stmt = $conn->prepare("UPDATE invoices SET status = 'paid', paid_at = NOW() WHERE id = ?");
        $stmt->bind_param("i", $invoiceId);
        $stmt->execute();
        $stmt->close();

        // Generate fresh hash
        // $newHash = generateInvoiceHash($invoiceId, $invoice['salt']);
        // header("Location: view_invoice.php?uuid=" . urlencode($uuid) . "&hash=" . urlencode($newHash));
        // exit();


        $newHash = generateInvoiceHash($invoiceId, $invoice['salt']);
        header("Location: /invoice/secure/" . urlencode($uuid) . "/" . urlencode($newHash));
        exit();
        
    } else {
        throw new Exception(json_encode($response->getErrors()));
    }
} catch (Exception $e) {
    http_response_code(500);
    echo "Payment failed: " . $e->getMessage();
    echo "<p><a href='view_invoice.php?uuid=" . urlencode($uuid) . "&hash=" . urlencode($clientHash) . "' class='btn btn-secondary'>← Back to Invoice</a></p>";
}

$conn->close();
