<?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 = '..';

$adId = isset($_GET['ad_id']) ? (int)$_GET['ad_id'] : 0;
$ad = [];
if ($adId > 0) {
    $ad = fetchRow("SELECT a.*, u.full_name, u.member_id FROM ads a JOIN users u ON a.created_by = u.id WHERE a.id = ?", [$adId]);
}

if (!$ad) {
    header('Location: submit.php');
    exit;
}

// Only the creator can pay
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;
}

$publicKey = paystack_public_key();
if (empty($publicKey)) {
    $paystackWarning = 'Paystack public key is not configured. Please set PAYSTACK_PUBLIC_KEY in your environment.';
}

// Compute amount in pesewas (Paystack amount is in kobo-equivalent)
$amount = (float)$ad['price'];
$amountKobo = (int)round($amount * 100);

// Get email for payer (from linked member if available)
$payerEmail = '';
if (!empty($ad['member_id'])) {
    $mem = fetchRow("SELECT email FROM members WHERE id = ?", [(int)$ad['member_id']]);
    if ($mem && !empty($mem['email'])) { $payerEmail = $mem['email']; }
}
if (empty($payerEmail)) {
    // Fallback to a placeholder (Paystack requires email)
    $payerEmail = 'noemail+' . $_SESSION['user_id'] . '@example.com';
}

// Ensure we have a payment reference
if (empty($ad['payment_reference'])) {
    $reference = 'AD-' . $adId . '-' . time();
    $ok = executeQuery("UPDATE ads SET payment_reference=? WHERE id=?", [$reference, $adId]);
    if ($ok) { $ad['payment_reference'] = $reference; }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pay for Advert - 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">
    <script src="https://js.paystack.co/v1/inline.js"></script>
</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="d-flex justify-content-between align-items-center mb-3">
                <h1 class="h2">Pay for Advertisement</h1>
                <a href="../index.php" class="btn btn-secondary">Back</a>
            </div>

            <?php if (!empty($paystackWarning)): ?>
                <div class="alert alert-warning"><?php echo htmlspecialchars($paystackWarning); ?></div>
            <?php endif; ?>

            <div class="card">
                <div class="card-body">
                    <div class="mb-3">
                        <strong>Title:</strong> <?php echo htmlspecialchars($ad['title']); ?>
                    </div>
                    <div class="mb-3">
                        <strong>Amount:</strong> GHS <?php echo number_format($amount, 2); ?>
                    </div>
                    <div class="mb-3">
                        <strong>Phone:</strong> <?php echo htmlspecialchars($ad['contact_phone']); ?>
                    </div>
                    <button id="payBtn" class="btn btn-primary" <?php echo empty($publicKey) ? 'disabled' : ''; ?>>Pay with Paystack</button>
                </div>
            </div>
        </main>
    </div>
</div>
<script>
    document.getElementById('payBtn').addEventListener('click', function() {
        var handler = PaystackPop.setup({
            key: '<?php echo $publicKey; ?>',
            email: '<?php echo htmlspecialchars($payerEmail); ?>',
            amount: <?php echo (int)$amountKobo; ?>,
            currency: 'GHS',
            channels: ['mobile_money', 'card'],
            ref: '<?php echo htmlspecialchars($ad['payment_reference']); ?>',
            metadata: {
                custom_fields: [
                    { display_name: 'Phone', variable_name: 'phone', value: '<?php echo htmlspecialchars($ad['contact_phone']); ?>' },
                    { display_name: 'Ad ID', variable_name: 'ad_id', value: '<?php echo (int)$adId; ?>' }
                ]
            },
            callback: function(response){
                window.location = 'verify_payment.php?ref=' + encodeURIComponent(response.reference);
            },
            onClose: function(){
                alert('Payment cancelled. You can try again.');
            }
        });
        handler.openIframe();
    });
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
