<?php
/**
 * organization/verify_payment.php
 * Called via POST after Paystack inline popup confirms payment.
 * Verifies the transaction with Paystack API, then credits the org wallet.
 */
session_start();

// Auth guard
if (empty($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'org_admin') {
    header("Location: login.php"); exit;
}

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/paystack.php';

$uid    = (int)$_SESSION['user_id'];
$org_id = (int)($_SESSION['organization_id'] ?? 0);

// ── Validate inputs ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: wallet.php"); exit;
}

if (!csrf_verify()) {
    header("Location: wallet.php?error=verify_failed"); exit;
}

$reference   = trim($_POST['reference'] ?? '');
$amount_kobo = (int)($_POST['amount_kobo'] ?? 0);

if (!$reference || $amount_kobo < 10000) { // minimum ₦100 = 10,000 kobo
    header("Location: wallet.php?error=verify_failed"); exit;
}

// ── Idempotency: ensure reference not already processed ───────────────────
$chk = $conn->prepare(
    "SELECT id FROM wallet_transactions
     WHERE reference = ? AND wallet_type = 'organization'
     LIMIT 1"
);
$chk->bind_param("s", $reference);
$chk->execute();
if ($chk->get_result()->num_rows > 0) {
    header("Location: wallet.php?error=already_used"); exit;
}

// ── Call Paystack API to verify ────────────────────────────────────────────
$ch = curl_init("https://api.paystack.co/transaction/verify/" . urlencode($reference));
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        "Authorization: Bearer " . PAYSTACK_SECRET,
        "Cache-Control: no-cache",
    ],
    CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);

if (!$response || $curl_err) {
    error_log("Paystack verify curl error: {$curl_err}");
    header("Location: wallet.php?error=verify_failed"); exit;
}

$data = json_decode($response, true);

// Paystack must return status=true and data.status='success'
if (!($data['status'] ?? false) || ($data['data']['status'] ?? '') !== 'success') {
    header("Location: wallet.php?error=verify_failed"); exit;
}

$tx_data        = $data['data'];
$paid_amount_kobo = (int)($tx_data['amount'] ?? 0);
$currency       = $tx_data['currency'] ?? '';
$customer_email = $tx_data['customer']['email'] ?? '';

// ── Verify amount and currency ────────────────────────────────────────────
if ($currency !== 'NGN') {
    header("Location: wallet.php?error=verify_failed"); exit;
}

// Allow ±1 kobo tolerance for floating-point edge cases
if (abs($paid_amount_kobo - $amount_kobo) > 1) {
    error_log("Paystack amount mismatch. Expected: {$amount_kobo}, Got: {$paid_amount_kobo}, Ref: {$reference}");
    header("Location: wallet.php?error=amount_mismatch"); exit;
}

// ── Verify this payment belongs to this org ────────────────────────────────
$metadata = $tx_data['metadata'] ?? [];
if (!empty($metadata['org_id']) && (int)$metadata['org_id'] !== $org_id) {
    error_log("Paystack org_id mismatch. Session: {$org_id}, Metadata: {$metadata['org_id']}, Ref: {$reference}");
    header("Location: wallet.php?error=verify_failed"); exit;
}

// ── All checks passed — credit org wallet ────────────────────────────────
$amount_naira = $paid_amount_kobo / 100;
$description  = "Wallet funded via Paystack — ₦" . number_format($amount_naira, 2);

try {
    credit_org_wallet($conn, $org_id, $uid, $amount_naira, $reference, $description);
} catch (Throwable $e) {
    error_log("Org wallet credit failed: " . $e->getMessage() . " Ref: {$reference}");
    header("Location: wallet.php?error=verify_failed"); exit;
}

// Optional bookkeeping — the wallet is ALREADY credited, so this must never
// change the outcome. It runs in its own try/catch and matches the real
// paystack_transactions columns; any difference between installs is ignored.
try {
    if ($pt = $conn->prepare(
        "INSERT INTO paystack_transactions (user_id, reference, amount, status, created_at)
         VALUES (?, ?, ?, 'success', NOW())"
    )) {
        $pt->bind_param("isd", $uid, $reference, $amount_naira);
        $pt->execute();
    }
} catch (Throwable $e) {
    error_log("paystack_transactions log skipped (non-fatal): " . $e->getMessage() . " Ref: {$reference}");
}

header("Location: wallet.php?funded=1&amount=" . urlencode($amount_naira));
exit;
