<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/Course.php';

requireLogin();
$user = getCurrentUser();

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
    setFlashMessage('error', 'Only students can enroll in courses.');
    header('Location: ' . APP_URL . '/lms/courses.php');
    exit;
}

$courseId = (int)($_GET['course_id'] ?? 0);
$courseModel = new Course();
$course = $courseModel->getById($courseId);

if (!$course) {
    setFlashMessage('error', 'Course not found.');
    header('Location: ' . APP_URL . '/lms/courses.php');
    exit;
}

$price = (float)($course['price'] ?? 0);

if ($price <= 0) {
    try {
        $courseModel->enroll($courseId, $user['id']);
        setFlashMessage('success', 'Enrolled successfully.');
    } catch (Exception $e) {
        setFlashMessage('error', $e->getMessage());
    }

    header('Location: ' . APP_URL . '/lms/courses.php');
    exit;
}

$db = Database::getInstance();

$existingEnrollment = $db->get(
    'SELECT id, status, payment_status FROM course_enrollments WHERE course_id = ? AND student_id = ? ORDER BY created_at DESC LIMIT 1',
    [$courseId, $user['id']]
);

if ($existingEnrollment && $existingEnrollment['payment_status'] === 'paid') {
    setFlashMessage('success', 'You are already enrolled in this course.');
    header('Location: ' . APP_URL . '/lms/dashboard.php');
    exit;
}

$pageTitle = 'Checkout - ' . htmlspecialchars($course['title']);
include __DIR__ . '/includes/header.php';
?>

<div class="container-xxl mb-4">
    <div class="row justify-content-center">
        <div class="col-lg-8 col-xl-7">
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="mb-0">Checkout</h5>
                        <small class="text-muted">Complete payment to access this course</small>
                    </div>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
                        <div>
                            <h3 class="h5 mb-1"><?php echo htmlspecialchars($course['title']); ?></h3>
                            <p class="text-muted mb-2"><?php echo htmlspecialchars($course['short_description'] ?? ''); ?></p>
                            <div class="small text-muted">
                                Instructor: <?php echo htmlspecialchars(($course['first_name'] ?? '') . ' ' . ($course['last_name'] ?? '')); ?>
                            </div>
                        </div>
                        <div class="text-end">
                            <div class="h4 mb-0 text-primary">
                                <?php echo htmlspecialchars(number_format($price, 2)); ?>
                                <?php echo htmlspecialchars($course['currency'] ?? 'USD'); ?>
                            </div>
                            <div class="small text-muted">Choose full or installment plan at checkout</div>
                        </div>
                    </div>

                    <hr class="my-4">

                    <div class="mb-3">
                        <h6 class="mb-1">Student</h6>
                        <div class="small text-muted">
                            <?php echo htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')); ?><br>
                            <?php echo htmlspecialchars($user['email'] ?? ''); ?>
                        </div>
                    </div>

                    <div class="mb-3">
                        <h6 class="mb-1">Payment options</h6>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="payment_plan" id="paymentPlanFull" value="full" checked>
                            <label class="form-check-label small" for="paymentPlanFull">
                                Pay full amount now (<?php echo htmlspecialchars(number_format($price, 2)); ?> <?php echo htmlspecialchars($course['currency'] ?? 'USD'); ?>)
                            </label>
                        </div>
                        <div class="form-check mt-1">
                            <input class="form-check-input" type="radio" name="payment_plan" id="paymentPlanInstallments" value="installments_5">
                            <label class="form-check-label small" for="paymentPlanInstallments">
                                Pay in 5 equal installments over 10 weeks. First payment is due now; the next 4 payments will be scheduled automatically every 2 weeks.
                            </label>
                        </div>
                    </div>

                    <div class="alert alert-info small">
                        After successful payment via Paystack or Square, your enrollment will be activated and the course will appear in your dashboard.
                    </div>

                    <div id="checkoutErrors" class="alert alert-danger d-none"></div>

                    <div class="mt-3">
                        <h6 class="mb-1 small">Policies &amp; Agreements</h6>
                        <p class="small text-muted mb-2">
                            You must read and agree to each of the following before proceeding with payment.
                        </p>

                        <div class="form-check mb-1">
                            <input class="form-check-input" type="checkbox" id="agreeTrainingPolicy">
                            <label class="form-check-label small" for="agreeTrainingPolicy">
                                I have read and agree to the
                                <button type="button" class="btn btn-link btn-sm p-0 align-baseline" data-bs-toggle="modal" data-bs-target="#trainingPolicyModal">
                                    Training Non-Compete &amp; Materials
                                </button>.
                            </label>
                        </div>

                        <div class="form-check mb-1">
                            <input class="form-check-input" type="checkbox" id="agreePaymentPolicy">
                            <label class="form-check-label small" for="agreePaymentPolicy">
                                I have read and agree to the
                                <button type="button" class="btn btn-link btn-sm p-0 align-baseline" data-bs-toggle="modal" data-bs-target="#paymentPolicyModal">
                                    Non-Refundable Payment Policy
                                </button>.
                            </label>
                        </div>

                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="agreePrivacyPolicy">
                            <label class="form-check-label small" for="agreePrivacyPolicy">
                                I have read and agree to the
                                <button type="button" class="btn btn-link btn-sm p-0 align-baseline" data-bs-toggle="modal" data-bs-target="#privacyPolicyModal">
                                    Data Privacy Policy
                                </button>.
                            </label>
                        </div>
                    </div>

                    <div class="mt-4 d-flex flex-wrap gap-2">
                        <button id="paystackPay" type="button" class="btn btn-primary">
                            <i class="ri ri-bank-card-line me-1"></i> Pay with Paystack
                        </button>
                        <?php if (strtoupper($course['currency'] ?? 'USD') === 'USD'): ?>
                            <button id="squarePay" type="button" class="btn btn-outline-secondary">
                                <i class="ri ri-bank-card-line me-1"></i> Pay with Square
                            </button>
                        <?php endif; ?>
                        <a href="<?php echo APP_URL; ?>/lms/courses.php" class="btn btn-link ms-auto">Cancel</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="trainingPolicyModal" tabindex="-1" aria-labelledby="trainingPolicyModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="trainingPolicyModalLabel">Training Non-Compete &amp; Materials</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0">
                <iframe src="<?php echo APP_URL; ?>/website/training-agreement.php?embed=1" title="Training Non-Compete &amp; Materials" style="border:0;width:100%;height:60vh;"></iframe>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="trainingPolicyAgreeBtn" data-bs-dismiss="modal">I Agree</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="paymentPolicyModal" tabindex="-1" aria-labelledby="paymentPolicyModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="paymentPolicyModalLabel">Non-Refundable Payment Policy</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0">
                <iframe src="<?php echo APP_URL; ?>/website/payment-policy.php?embed=1" title="Non-Refundable Payment Policy" style="border:0;width:100%;height:60vh;"></iframe>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="paymentPolicyAgreeBtn" data-bs-dismiss="modal">I Agree</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="privacyPolicyModal" tabindex="-1" aria-labelledby="privacyPolicyModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="privacyPolicyModalLabel">Data Privacy Policy</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0">
                <iframe src="<?php echo APP_URL; ?>/website/privacy-policy.php?embed=1" title="Data Privacy Policy" style="border:0;width:100%;height:60vh;"></iframe>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="privacyPolicyAgreeBtn" data-bs-dismiss="modal">I Agree</button>
            </div>
        </div>
    </div>
</div>

<script>
const courseId = <?php echo (int)$course['id']; ?>;
const coursePrice = <?php echo json_encode((float)$price); ?>;
const currency = <?php echo json_encode($course['currency'] ?? 'USD'); ?>;
const studentFirstName = <?php echo json_encode($user['first_name'] ?? ''); ?>;
const studentLastName = <?php echo json_encode($user['last_name'] ?? ''); ?>;
const studentEmail = <?php echo json_encode($user['email'] ?? ''); ?>;
const PAYSTACK_PUBLIC_KEY = <?php echo json_encode(PAYSTACK_PUBLIC_KEY); ?>;
const SQUARE_APPLICATION_ID = <?php echo json_encode(defined('SQUARE_APPLICATION_ID') ? SQUARE_APPLICATION_ID : ''); ?>;

document.addEventListener('DOMContentLoaded', function () {
    const trainingAgreeBtn = document.getElementById('trainingPolicyAgreeBtn');
    if (trainingAgreeBtn) {
        trainingAgreeBtn.addEventListener('click', function () {
            const cb = document.getElementById('agreeTrainingPolicy');
            if (cb) cb.checked = true;
        });
    }

    const paymentAgreeBtn = document.getElementById('paymentPolicyAgreeBtn');
    if (paymentAgreeBtn) {
        paymentAgreeBtn.addEventListener('click', function () {
            const cb = document.getElementById('agreePaymentPolicy');
            if (cb) cb.checked = true;
        });
    }

    const privacyAgreeBtn = document.getElementById('privacyPolicyAgreeBtn');
    if (privacyAgreeBtn) {
        privacyAgreeBtn.addEventListener('click', function () {
            const cb = document.getElementById('agreePrivacyPolicy');
            if (cb) cb.checked = true;
        });
    }
});

function showError(message) {
    const box = document.getElementById('checkoutErrors');
    if (!box) return;
    if (!message) {
        box.classList.add('d-none');
        box.textContent = '';
    } else {
        box.classList.remove('d-none');
        box.textContent = message;
    }
}

function ensureTermsAccepted() {
    const training = document.getElementById('agreeTrainingPolicy');
    const payment = document.getElementById('agreePaymentPolicy');
    const privacy = document.getElementById('agreePrivacyPolicy');

    if (!training || !payment || !privacy) {
        showError('Unable to verify policy agreements. Please reload the page and try again.');
        return false;
    }

    const missing = [];
    if (!training.checked) missing.push('Training Non-Compete & Materials');
    if (!payment.checked) missing.push('Non-Refundable Payment Policy');
    if (!privacy.checked) missing.push('Data Privacy Policy');

    if (missing.length > 0) {
        showError('You must read and agree to: ' + missing.join(', ') + ' before proceeding with payment.');
        return false;
    }

    return true;
}

function getSelectedPaymentPlan() {
    const radios = document.querySelectorAll('input[name="payment_plan"]');
    for (const r of radios) {
        if (r.checked) {
            return r.value || 'full';
        }
    }
    return 'full';
}

async function createEnrollment() {
    const res = await fetch('<?php echo APP_URL; ?>/website/api/enroll.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            course_id: courseId,
            payment_plan: getSelectedPaymentPlan()
        })
    });

    const text = await res.text();
    if (!text) {
        return { success: false, message: 'Empty response from enrollment API.' };
    }

    // Try to parse JSON directly, then fall back to slicing from first JSON token
    try {
        const cleaned = text
            .replace(/^[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+/, '')
            .replace(/[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+$/, '');
        return JSON.parse(cleaned);
    } catch (e1) {
        try {
            const idx = Math.min(
                ...['{', '[']
                    .map(ch => {
                        const i = text.indexOf(ch);
                        return i === -1 ? Number.MAX_SAFE_INTEGER : i;
                    })
            );
            if (idx !== Number.MAX_SAFE_INTEGER) {
                const sliced = text.slice(idx)
                    .replace(/[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+$/, '');
                return JSON.parse(sliced);
            }
        } catch (e2) {
            // ignore and fall through
        }
        console.error('Enrollment API non-JSON response:', text);
        return {
            success: false,
            message: 'Enrollment API error: ' + text.substring(0, 200)
        };
    }
}

async function signAgreement(enrollmentId, fullName) {
    const res = await fetch('<?php echo APP_URL; ?>/website/api/enrollment_agreement_sign.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            enrollment_id: enrollmentId,
            full_name: fullName,
            email: studentEmail
        })
    });

    const text = await res.text();
    if (!text) {
        return { success: false, message: 'Empty response from agreement API.' };
    }

    try {
        const cleaned = text.replace(/^[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+/, '');
        return JSON.parse(cleaned);
    } catch (e1) {
        try {
            const idx = Math.min(
                ...['{', '[']
                    .map(ch => {
                        const i = text.indexOf(ch);
                        return i === -1 ? Number.MAX_SAFE_INTEGER : i;
                    })
            );
            if (idx !== Number.MAX_SAFE_INTEGER) {
                const sliced = text.slice(idx);
                return JSON.parse(sliced);
            }
        } catch (e2) {
            // ignore and fall through
        }
        console.error('Agreement API non-JSON response:', text);
        return {
            success: false,
            message: 'Agreement API error: ' + text.substring(0, 200)
        };
    }
}

async function acceptPaymentPolicy(enrollmentId, fullName) {
    const res = await fetch('<?php echo APP_URL; ?>/website/api/payment_policy_accept.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            enrollment_id: enrollmentId,
            full_name: fullName,
            email: studentEmail
        })
    });

    const text = await res.text();
    if (!text) {
        return { success: false, message: 'Empty response from payment policy API.' };
    }

    try {
        const cleaned = text.replace(/^[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+/, '');
        return JSON.parse(cleaned);
    } catch (e1) {
        try {
            const idx = Math.min(
                ...['{', '[']
                    .map(ch => {
                        const i = text.indexOf(ch);
                        return i === -1 ? Number.MAX_SAFE_INTEGER : i;
                    })
            );
            if (idx !== Number.MAX_SAFE_INTEGER) {
                const sliced = text.slice(idx);
                return JSON.parse(sliced);
            }
        } catch (e2) {
            // ignore and fall through
        }
        console.error('Payment policy API non-JSON response:', text);
        return {
            success: false,
            message: 'Payment policy API error: ' + text.substring(0, 200)
        };
    }
}

async function acceptPrivacyPolicy(enrollmentId, fullName) {
    const res = await fetch('<?php echo APP_URL; ?>/website/api/privacy_policy_accept.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            enrollment_id: enrollmentId,
            full_name: fullName,
            email: studentEmail
        })
    });

    const text = await res.text();
    if (!text) {
        return { success: false, message: 'Empty response from privacy policy API.' };
    }

    try {
        const cleaned = text.replace(/^[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+/, '');
        return JSON.parse(cleaned);
    } catch (e1) {
        try {
            const idx = Math.min(
                ...['{', '[']
                    .map(ch => {
                        const i = text.indexOf(ch);
                        return i === -1 ? Number.MAX_SAFE_INTEGER : i;
                    })
            );
            if (idx !== Number.MAX_SAFE_INTEGER) {
                const sliced = text.slice(idx);
                return JSON.parse(sliced);
            }
        } catch (e2) {
            // ignore and fall through
        }
        console.error('Privacy policy API non-JSON response:', text);
        return {
            success: false,
            message: 'Privacy policy API error: ' + text.substring(0, 200)
        };
    }
}

async function initPaystack(enrollmentId) {
    const r = await fetch('<?php echo APP_URL; ?>/website/api/paystack/init.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enrollment_id: enrollmentId })
    });
    const text = await r.text();
    let data;
    try {
        const cleaned = text
            .replace(/^[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+/, '')
            .replace(/[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+$/, '');
        data = cleaned ? JSON.parse(cleaned) : null;
    } catch (e1) {
        try {
            const idx = Math.min(
                ...['{', '[']
                    .map(ch => {
                        const i = text.indexOf(ch);
                        return i === -1 ? Number.MAX_SAFE_INTEGER : i;
                    })
            );
            if (idx !== Number.MAX_SAFE_INTEGER) {
                const sliced = text.slice(idx)
                    .replace(/[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+$/, '');
                data = JSON.parse(sliced);
            }
        } catch (e2) {
            // ignore and fall through
        }
    }

    if (!data || !data.success) {
        const msg = data && data.message ? data.message : ('Raw response: ' + text.substring(0, 200));
        showError('Paystack init failed: ' + msg);
        return;
    }
    if (typeof PaystackPop === 'undefined' || !window.PaystackPop) {
        showError('Paystack SDK failed to load.');
        return;
    }
    const txCurrency = (data.currency || currency || 'NGN').toUpperCase();

    const handler = PaystackPop.setup({
        key: data.public_key,
        email: data.customer_email,
        amount: data.amount * 100,
        // Ensure Paystack uses the same currency as the enrollment/payment amount
        currency: txCurrency,
        ref: data.reference,
        onClose: function () {},
        callback: function (response) {
            (async () => {
                try {
                    const v = await fetch('<?php echo APP_URL; ?>/website/api/paystack/verify.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            reference: response.reference,
                            enrollment_id: enrollmentId
                        })
                    });
                    const vText = await v.text();
                    let vr = null;
                    try {
                        const cleaned = vText
                            .replace(/^[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+/, '')
                            .replace(/[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+$/, '');
                        vr = cleaned ? JSON.parse(cleaned) : null;
                    } catch (e1) {
                        try {
                            const idx = Math.min(
                                ...['{', '[']
                                    .map(ch => {
                                        const i = vText.indexOf(ch);
                                        return i === -1 ? Number.MAX_SAFE_INTEGER : i;
                                    })
                            );
                            if (idx !== Number.MAX_SAFE_INTEGER) {
                                const sliced = vText.slice(idx)
                                    .replace(/[\u0000-\u001F\u007F-\u009F\u200B\uFEFF\s]+$/, '');
                                vr = JSON.parse(sliced);
                            }
                        } catch (e2) {
                            // ignore and fall through
                        }
                    }

                    if (vr && vr.success) {
                        window.location.href = '<?php echo APP_URL; ?>/lms/dashboard.php';
                    } else {
                        const msg = vr && vr.message ? vr.message : ('Raw response: ' + vText.substring(0, 200));
                        showError('Payment verification failed. ' + msg);
                    }
                } catch (e) {
                    showError('Error verifying payment.');
                }
            })();
        }
    });
    handler.openIframe();
}
function loadPaystackSdk(enrollmentId) {
    if (typeof PaystackPop !== 'undefined') {
        initPaystack(enrollmentId);
        return;
    }
    const s = document.createElement('script');
    s.src = 'https://js.paystack.co/v1/inline.js';
    s.onload = function () { initPaystack(enrollmentId); };
    s.onerror = function () { showError('Failed to load Paystack payment widget.'); };
    document.head.appendChild(s);
}

async function handlePaystack() {
    if (!PAYSTACK_PUBLIC_KEY || PAYSTACK_PUBLIC_KEY.indexOf('your-paystack') !== -1) {
        showError('Paystack is not configured on this site.');
        return;
    }
    if (!ensureTermsAccepted()) return;
    showError(null);
    try {
        const enroll = await createEnrollment();
        if (!enroll.success) {
            showError(enroll.message || 'Failed to create enrollment.');
            return;
        }
        const fullName = (studentFirstName + ' ' + studentLastName).trim() || studentEmail;

        const agreement = await signAgreement(enroll.enrollment_id, fullName);
        if (!agreement.success) {
            showError(agreement.message || 'Failed to sign training agreement.');
            return;
        }

        const paymentPolicy = await acceptPaymentPolicy(enroll.enrollment_id, fullName);
        if (!paymentPolicy.success) {
            showError(paymentPolicy.message || 'Failed to record acceptance of the Non-Refundable Payment Policy.');
            return;
        }

        const privacyPolicy = await acceptPrivacyPolicy(enroll.enrollment_id, fullName);
        if (!privacyPolicy.success) {
            showError(privacyPolicy.message || 'Failed to record acceptance of the Data Privacy Policy.');
            return;
        }

        loadPaystackSdk(enroll.enrollment_id);
    } catch (e) {
        showError('Unexpected error while starting Paystack payment.');
    }
}

const paystackBtn = document.getElementById('paystackPay');
if (paystackBtn) {
    paystackBtn.addEventListener('click', handlePaystack);
}

async function handleSquare() {
    if (!SQUARE_APPLICATION_ID) {
        showError('Square is not configured on this site.');
        return;
    }
    if (!ensureTermsAccepted()) return;
    showError(null);
    try {
        const enroll = await createEnrollment();
        if (!enroll.success) {
            showError(enroll.message || 'Failed to create enrollment.');
            return;
        }
        const fullName = (studentFirstName + ' ' + studentLastName).trim() || studentEmail;

        const agreement = await signAgreement(enroll.enrollment_id, fullName);
        if (!agreement.success) {
            showError(agreement.message || 'Failed to sign training agreement.');
            return;
        }

        const paymentPolicy = await acceptPaymentPolicy(enroll.enrollment_id, fullName);
        if (!paymentPolicy.success) {
            showError(paymentPolicy.message || 'Failed to record acceptance of the Non-Refundable Payment Policy.');
            return;
        }

        const privacyPolicy = await acceptPrivacyPolicy(enroll.enrollment_id, fullName);
        if (!privacyPolicy.success) {
            showError(privacyPolicy.message || 'Failed to record acceptance of the Data Privacy Policy.');
            return;
        }

        const r = await fetch('<?php echo APP_URL; ?>/website/api/square/initialize.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ enrollment_id: enroll.enrollment_id })
        });

        const text = await r.text();
        let data;
        try {
            data = text ? JSON.parse(text) : null;
        } catch (parseErr) {
            console.error('Square init non-JSON response:', text);
            showError('Square init failed. Raw response: ' + text.substring(0, 200));
            return;
        }

        if (!data || !data.success || !data.checkout_url) {
            const msg = (data && data.message) ? data.message : 'Failed to start Square payment.';
            showError(msg);
            return;
        }

        window.location.href = data.checkout_url;
    } catch (e) {
        console.error('Square payment error:', e);
        const msg = (e && e.message) ? e.message : 'Unexpected error while starting Square payment. Check browser console for details.';
        showError('Square error: ' + msg);
    }
}

const squareBtn = document.getElementById('squarePay');
if (squareBtn) {
    squareBtn.addEventListener('click', handleSquare);
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
