<?php
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../config/logger.php';
require_once '../config/paystack.php';

requireLogin();
requireRole(['admin','diocesan_chairman','diocese_chairman','diocesan_secretary','diocesan_treasurer','diocesan_dom','diocesan_music_director']);

$basePath = '..';

$ref = isset($_GET['ref']) ? trim($_GET['ref']) : '';
if ($ref === '') {
    header('Location: ../index.php');
    exit;
}

$ad = fetchRow("SELECT * FROM ads WHERE payment_reference = ?", [$ref]);
if (!$ad) {
    header('Location: ../index.php');
    exit;
}

if ($ad['created_by'] != $_SESSION['user_id']) {
    header('Location: ../access-denied.php');
    exit;
}

if ($ad['workflow_state'] !== 'payment_pending' || $ad['status'] !== 'pending') {
    header('Location: manage.php');
    exit;
}

$secretKey = paystack_secret_key();
if (empty($secretKey)) {
    $verifyError = 'Paystack secret key not configured. Set PAYSTACK_SECRET_KEY.';
} else {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.paystack.co/transaction/verify/' . rawurlencode($ref));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $secretKey,
        'Cache-Control: no-cache'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr = curl_error($ch);
    curl_close($ch);

    if ($result === false || $httpCode !== 200) {
        $verifyError = 'Payment verification failed.';
    } else {
        $resp = json_decode($result, true);
        if (!$resp || empty($resp['status'])) {
            $verifyError = 'Invalid response from payment gateway.';
        } else {
            $data = $resp['data'] ?? [];
            $success = isset($data['status']) && $data['status'] === 'success';
            $amountPaid = isset($data['amount']) ? (int)$data['amount'] : 0; // in pesewas
            $expected = (int)round(((float)$ad['price']) * 100);
            if ($success && $amountPaid >= $expected) {
                executeQuery("UPDATE ads SET payment_status='paid', workflow_state='pending_approval' WHERE id=?", [(int)$ad['id']]);
                $tbl = fetchRow("SHOW TABLES LIKE 'ad_payments'");
                if ($tbl) {
                    executeQuery(
                        "INSERT INTO ad_payments (ad_id, user_id, amount, payment_status, payment_reference) VALUES (?,?,?,?,?)",
                        [ (int)$ad['id'], (int)$_SESSION['user_id'], ((float)$amountPaid)/100.0, 'paid', $ref ]
                    );
                }
                header('Location: manage.php?paid=1');
                exit;
            } else {
                $verifyError = 'Payment not successful or amount mismatch.';
                executeQuery("UPDATE ads SET payment_status='failed' WHERE id=?", [(int)$ad['id']]);
                $tbl = fetchRow("SHOW TABLES LIKE 'ad_payments'");
                if ($tbl) {
                    executeQuery(
                        "INSERT INTO ad_payments (ad_id, user_id, amount, payment_status, payment_reference) VALUES (?,?,?,?,?)",
                        [ (int)$ad['id'], (int)$_SESSION['user_id'], ((float)$amountPaid)/100.0, 'failed', $ref ]
                    );
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Payment - GHAMECC</title>
    <?php include '../includes/favicon.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<?php include '../includes/navbar.php'; ?>
<div class="container-fluid">
    <div class="row">
        <?php include '../includes/sidebar.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
            <div class="alert alert-danger"><?php echo htmlspecialchars($verifyError ?? 'Payment verification error'); ?></div>
            <a href="pay.php?ad_id=<?php echo (int)$ad['id']; ?>" class="btn btn-secondary">Back to Payment</a>
        </main>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
