<?php

// DEBUG (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// REQUIRED FILES
require 'config.php';
require 'vendor/autoload.php';

// Allow only POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die("Method Not Allowed");
}

// -----------------------------------------------------
// STEP 1 — COLLECT POST DATA
// -----------------------------------------------------
$invoiceId       = $_POST['invoice_id'] ?? null;
$uuid            = $_POST['uuid'] ?? null;
$clientHash      = $_POST['hash'] ?? null;
$paymentIntentId = $_POST['payment_intent_id'] ?? null;
$amount          = $_POST['amount'] ?? null;

if (!$invoiceId || !$uuid || !$clientHash || !$paymentIntentId) {
    http_response_code(400);
    die("Missing required fields.");
}

// -----------------------------------------------------
// STEP 2 — DB CONNECTION
// -----------------------------------------------------
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die("DB Error: " . $conn->connect_error);
}

// -----------------------------------------------------
// STEP 3 — GET PAYMENT METHOD ID FROM INVOICE
// -----------------------------------------------------
$pmStmt = $conn->prepare("SELECT payment_method_id, payment_method FROM invoices WHERE id = ?");
$pmStmt->bind_param("i", $invoiceId);
$pmStmt->execute();
$invRes = $pmStmt->get_result();
$inv = $invRes->fetch_assoc();
$pmStmt->close();

if (!$inv) {
    die("Invoice not found.");
}

// default mapping
$defaultIds = [
    'square' => 1,
    'stripe' => 2,
    'paypal' => 3
];

$pmId = $inv['payment_method_id'];

// if missing → auto-assign
if (empty($pmId)) {
    $paymentMethod = strtolower($inv['payment_method'] ?? 'stripe');
    $pmId = $defaultIds[$paymentMethod] ?? 2; // default stripe
}

// -----------------------------------------------------
// STEP 4 — LOAD PAYMENT METHOD KEYS FROM DB
// -----------------------------------------------------
$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();

if (!$gateway) {
    die("Payment method configuration missing.");
}

// Set Stripe keys dynamically
define("STRIPE_SECRET_KEY", $gateway['stripe_secret_key'] ?? "");
define("STRIPE_PUBLISHABLE_KEY", $gateway['stripe_public_key'] ?? "");


//stripe testing keys
// define("STRIPE_SECRET_KEY", "sk_test_51NxGHQIrZYESSIgqOH9qryUbDk14t7YGfH0R2EEGVOVkPRcSkxIS1zeZ1LxNiU82e2ZHnbXHbZ1Ur5xUZMRUZGQk00WSXtcCIU" ?? ""); 
// define("STRIPE_PUBLISHABLE_KEY", "pk_test_51NxGHQIrZYESSIgqn72APBOFuFvtSvUKPNgbeej7IJZVZpFMdQZkKL7lTPeX1MarPQ1nv78DNe6FJrvQGz6WOTxp00KWfGXbA9" ?? "");

if (empty(STRIPE_SECRET_KEY)) {
    die("Stripe keys missing.");
}

// -----------------------------------------------------
// STEP 5 — VERIFY PAYMENT INTENT WITH STRIPE
// -----------------------------------------------------
\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

try {
    $intent = \Stripe\PaymentIntent::retrieve($paymentIntentId);

    // local amount
    $localAmount = (int)round((float)$amount * 100);

    // verify amount
    if ($intent->amount !== $localAmount) {
        throw new Exception("Amount mismatch.");
    }

    // verify succeeded
    if ($intent->status !== "succeeded") {
        throw new Exception("Payment not completed.");
    }

} catch (\Stripe\Exception\ApiErrorException $e) {
    http_response_code(500);
    die("Stripe API Error: " . $e->getMessage());

} catch (Exception $e) {
    http_response_code(500);
    die("Payment verification failed: " . $e->getMessage());
}


// -----------------------------------------------------
// STEP 6 — UPDATE INVOICE AS PAID
// -----------------------------------------------------
$stmt = $conn->prepare(
    "UPDATE invoices 
     SET status = 'paid', paid_at = NOW(), stripe_transaction_id = ? 
     WHERE id = ?"
);
$stmt->bind_param("si", $paymentIntentId, $invoiceId);
$stmt->execute();
$stmt->close();

$conn->close();

// -----------------------------------------------------
// STEP 7 — REDIRECT TO SECURE INVOICE PAGE
// -----------------------------------------------------
$redirectUrl = "/invoice/secure/" . urlencode($uuid) . "/" . urlencode($clientHash);
header("Location: $redirectUrl");
exit;

?>
