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

$courseId = (int)($_GET['course_id'] ?? 0);
$db = Database::getInstance();
$course = null;

if ($courseId) {
    $course = $db->get("SELECT c.*, cat.name as category_name, u.first_name, u.last_name FROM courses c LEFT JOIN categories cat ON c.category_id = cat.id LEFT JOIN users u ON c.instructor_id = u.id WHERE c.id = ? AND c.status = 'published'", [$courseId]);
}

if (!$course) {
    header('HTTP/1.1 404 Not Found');
    echo "<h1>Course not found</h1>";
    exit;
}

$baseUrl = defined('APP_URL') ? rtrim(APP_URL, '/') : '';
$thumb = $course['thumbnail'] ?? '';
$thumbSrc = $baseUrl . '/assets/images/course-placeholder.jpg';
if ($thumb) {
    if (stripos($thumb, 'http') === 0) {
        $thumbSrc = $thumb;
    } elseif (file_exists(__DIR__ . '/../' . ltrim($thumb, '/'))) {
        $thumbSrc = $baseUrl . '/' . ltrim($thumb, '/');
    } elseif (file_exists(__DIR__ . '/../uploads/courses/' . basename($thumb))) {
        $thumbSrc = $baseUrl . '/uploads/courses/' . basename($thumb);
    }
}

// minimal page
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($course['title']); ?> - <?php sc_text('site', 'meta_title', APP_NAME, $region); ?></title>
    <!-- Core CSS frameworks -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Project styles -->
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/modern-ux.css">
    <link rel="stylesheet" href="../assets/css/page-styles.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800,900&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700,800&display=swap" rel="stylesheet">

    <style>
        /* Ensure content clears fixed banner + header (JS sets exact padding) */
        main { padding-top: 140px; }
        /* Constrain large course thumbnails and keep responsive */
        .course-detail-thumb { max-height: 60vh; width: 100%; max-width: 100%; object-fit: contain; display: block; margin: 0 auto; }
        /* Ensure our custom modal is above the header and interactive */
        #checkoutModal { z-index: 11050 !important; pointer-events: auto !important; }
        #checkoutModal .modal-dialog { max-width: 800px; width: 100%; pointer-events: auto; }
        /* Make sure header/banner are below the modal */
        .regional-banner, .modern-header, .scroll-progress { z-index: 1010; }
    </style>
</head>
<body>
    <div class="scroll-progress" id="scrollProgress"></div>

    <!-- Regional Selector Banner -->
    <div class="regional-banner">
        <div class="container">
            <div class="region-selector">
                <span class="region-label">Select Your Region:</span>
                <div class="region-options">
                    <button class="region-btn <?php echo ($region === 'usa') ? 'active' : ''; ?>" data-region="usa">🇺🇸 USA</button>
                    <button class="region-btn <?php echo ($region === 'europe') ? 'active' : ''; ?>" data-region="europe">🇪🇺 Europe</button>
                    <button class="region-btn <?php echo ($region === 'africa') ? 'active' : ''; ?>" data-region="africa">🌍 Africa</button>
                </div>
            </div>
        </div>
    </div>

    <header class="modern-header">
        <nav class="navbar navbar-expand-lg">
            <div class="container">
                <a class="navbar-brand" href="index.php">
                    <div class="brand-logo">
                        <img src="../assets/images/logo.png" alt="SmartThink3" class="logo-img">
                        <span class="brand-text">SmartThink3</span>
                    </div>
                </a>

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="mainNav">
                    <ul class="navbar-nav mx-auto">
                        <li class="nav-item"><a class="nav-link" href="index.php">Home</a></li>
                        <li class="nav-item"><a class="nav-link" href="about.php">About Us</a></li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="services.php" id="servicesDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Services</a>
                            <ul class="dropdown-menu" aria-labelledby="servicesDropdown">
                                <li><a class="dropdown-item" href="training.php">Training</a></li>
                                <li><a class="dropdown-item" href="consulting.php">Consulting</a></li>
                                <li><a class="dropdown-item" href="recruitment.php">Recruitment</a></li>
                            </ul>
                        </li>
                        <li class="nav-item"><a class="nav-link active" href="courses.php">Courses</a></li>

                        <li class="nav-item"><a class="nav-link" href="contact.php">Contact Us</a></li>
                    </ul>
                    <ul class="navbar-nav ms-auto">
                        <li class="nav-item">
                            <a class="nav-link login-btn" href="../lms/login.php">
                                <i class="fas fa-sign-in-alt"></i> Login
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>

    <main class="py-5" style="padding-top:140px;">
        <div class="container">
            <div class="row g-4">
                <div class="col-lg-6">
                    <div class="card">
                        <img src="<?php echo htmlspecialchars($thumbSrc); ?>" alt="<?php echo htmlspecialchars($course['title']); ?>" class="card-img-top img-fluid course-detail-thumb">
                    </div> 
                </div>
                <div class="col-lg-6">
                    <h1 class="display-6"><?php echo htmlspecialchars($course['title']); ?></h1>
                    <p class="text-muted"><?php echo htmlspecialchars($course['short_description'] ?? $course['description'] ?? ''); ?></p>
                    <p><strong>Instructor:</strong> <?php echo htmlspecialchars($course['first_name'] . ' ' . $course['last_name']); ?></p>
                    <p><strong>Category:</strong> <?php echo htmlspecialchars($course['category_name']); ?></p>
                    <p><strong>Price:</strong> <span class="h5 text-primary"><?php echo ($course['price'] > 0) ? ('$' . number_format($course['price'], 2)) : 'Free'; ?></span></p>

                    <div class="mt-4">
                        <button id="enrollNow" class="btn btn-primary btn-lg">Enroll / Checkout</button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="main-footer mt-5">
        <div class="container">
            <div class="row">
                <div class="col-lg-4">
                    <div class="footer-brand">
                        <img src="../assets/images/logo-white.png" alt="SmartThink3" class="footer-logo">
                        <p><?php sc_html('home', 'footer_about', 'Empowering learners globally with cutting-edge educational technology and world-class content.', $region); ?></p>
                        <div class="social-links">
                            <a href="#"><i class="fab fa-facebook"></i></a>
                            <a href="#"><i class="fab fa-twitter"></i></a>
                            <a href="#"><i class="fab fa-linkedin"></i></a>
                            <a href="#"><i class="fab fa-instagram"></i></a>
                        </div>
                    </div>
                </div>
                <div class="col-lg-2">
                    <div class="footer-links">
                        <h4>Quick Links</h4>
                        <ul>
                            <li><a href="index.php">Home</a></li>
                            <li><a href="about.php">About Us</a></li>
                            <li><a href="courses.php">Courses</a></li>
                            <li><a href="services.php">Services</a></li>
                        </ul>
                    </div>
                </div>
                <div class="col-lg-2">
                    <div class="footer-links">
                        <h4>Resources</h4>
                        <ul>
                            <li><a href="#">FAQs</a></li>
                            <li><a href="#">Support</a></li>
                            <li><a href="#">Careers</a></li>
                        </ul>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="footer-newsletter">
                        <h4>Subscribe to Our Newsletter</h4>
                        <p>Get the latest updates on courses and features</p>
                        <form class="newsletter-form">
                            <input type="email" placeholder="Your email address">
                            <button type="submit">Subscribe</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/main.js"></script>

    <!-- Checkout Modal (keeps same modal markup and JS) -->
    <!-- Modal -->
    <div id="checkoutModal" class="modal" role="dialog" aria-modal="true" style="display:none; position:fixed; left:0; top:0; right:0; bottom:0; background:rgba(0,0,0,0.5); align-items:center; justify-content:center; z-index:11050; pointer-events:auto;">
        <div class="modal-dialog" style="background:#fff; padding:20px; max-width:600px; width:100%; border-radius:8px;">
            <h3>Checkout</h3>
            <div id="checkoutErrors" style="color:red; display:none;"></div>

            <div id="guestFields">
                <div class="row">
                    <div class="col-md-6 mb-2">
                        <label>First name</label>
                        <input id="guestFirstName" type="text" class="form-control" autofocus>
                    </div>
                    <div class="col-md-6 mb-2">
                        <label>Last name</label>
                        <input id="guestLastName" type="text" class="form-control">
                    </div>
                </div>
                <div class="mb-2">
                    <label>Email</label>
                    <input id="guestEmail" type="email" class="form-control">
                </div>
                <div class="row">
                    <div class="col-md-6 mb-2">
                        <label>Password (optional)</label>
                        <input id="guestPassword" type="password" class="form-control" placeholder="Choose a password to create an account">
                    </div>
                    <div class="col-md-6 mb-2">
                        <label>Confirm password</label>
                        <input id="guestPasswordConfirm" type="password" class="form-control" placeholder="Repeat password">
                    </div>
                </div>
                <small class="text-muted">If this email already has an account, the enrollment will be attached to that account. If no account exists, one will be created for you.</small>
            </div>

            <div id="paymentMethods">
                <h5>Pay with</h5>
                <div id="paypalButtonContainer"></div>
                <button id="paystackPay" class="btn btn-outline-primary mt-3">Pay with Paystack</button>
            </div>

            <div class="mt-3">
                <button id="closeModal" class="btn btn-secondary">Close</button>
            </div>
        </div>
    </div>

<script>
const courseId = <?php echo (int)$course['id']; ?>;
const coursePrice = <?php echo (float)$course['price']; ?>;
const currency = '<?php echo $course['currency'] ?? 'USD'; ?>';
const PAYPAL_CLIENT_ID = '<?php echo PAYPAL_CLIENT_ID; ?>';
const PAYSTACK_PUBLIC_KEY = '<?php echo PAYSTACK_PUBLIC_KEY; ?>';

function showModal() {
    // Ensure header offset is correct before showing
    adjustBodyForHeader();

    const modal = document.getElementById('checkoutModal');
    modal.style.display = 'flex';
    // prevent body scrolling while modal is open
    document.body.style.overflow = 'hidden';

    // Render PayPal buttons after modal is visible (idempotent in loadPayPal)
    if (coursePrice > 0) loadPayPal();

    // Focus first field and debug element under modal center (helps detect blocking overlays)
    setTimeout(() => {
        const first = document.getElementById('guestFirstName');
        if (first) {
            try { first.focus(); } catch (e) { console.log('focus failed', e); }
        }
        // diagnostic: find the topmost element at the modal content center
        const rect = modal.getBoundingClientRect();
        const cx = Math.round(rect.left + rect.width / 2);
        const cy = Math.round(rect.top + (rect.height > 0 ? 50 : window.innerHeight / 2));
        const el = document.elementFromPoint(cx, cy);
        if (el && !modal.contains(el)) {
            console.warn('Element overlapping modal center:', el);
            // temporarily highlight it for visual debugging
            el.style.outline = '3px solid rgba(255,0,0,0.85)';
            setTimeout(() => { el.style.outline = ''; }, 2500);
        }
    }, 50);
}
function hideModal() { document.getElementById('checkoutModal').style.display = 'none'; document.body.style.overflow = ''; }

document.getElementById('enrollNow').addEventListener('click', showModal);
document.getElementById('closeModal').addEventListener('click', hideModal);

// Create enrollment (guest) then initialize payment UI
async function createEnrollment(first_name, last_name, email, password) {
    const res = await fetch('/website/api/enroll.php', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ course_id: courseId, first_name: first_name, last_name: last_name, email: email, password: password })
    });
    return res.json();
}

// PayPal button rendering (client-side)
function loadPayPal() {
    if (!coursePrice || coursePrice <= 0) return;
    // If PayPal is not configured in config/database.php, show a notice instead of loading SDK
    if (!PAYPAL_CLIENT_ID || PAYPAL_CLIENT_ID.indexOf('your-paypal') !== -1) {
        document.getElementById('paypalButtonContainer').innerHTML = '<div class="text-muted small">PayPal is not configured for this site.</div>';
        return;
    }
    document.getElementById('paypalButtonContainer').innerHTML = '<div class="small text-muted">Loading PayPal...</div>';
    const script = document.createElement('script');
    script.src = `https://www.paypal.com/sdk/js?client-id=${encodeURIComponent(PAYPAL_CLIENT_ID)}&currency=${encodeURIComponent(currency)}`;
    script.onload = () => {
        // clear message
        document.getElementById('paypalButtonContainer').innerHTML = '';
        paypal.Buttons({
            createOrder: async function(data, actions) {
                // create enrollment first if not created
                const firstName = document.getElementById('guestFirstName').value;
                const lastName = document.getElementById('guestLastName').value;
                const email = document.getElementById('guestEmail').value;
                const password = document.getElementById('guestPassword').value;
                const passwordConfirm = document.getElementById('guestPasswordConfirm').value;
                if (password && password !== passwordConfirm) {
                    document.getElementById('checkoutErrors').innerText = 'Passwords do not match';
                    document.getElementById('checkoutErrors').style.display = 'block';
                    throw new Error('Password mismatch');
                }
                const enroll = await createEnrollment(firstName, lastName, email, password);
                if (!enroll.success) {
                    document.getElementById('checkoutErrors').innerText = enroll.message || 'Failed to create enrollment';
                    document.getElementById('checkoutErrors').style.display = 'block';
                    throw new Error('Enrollment failed');
                }
                window._enrollmentId = enroll.enrollment_id;
                const r = await fetch('/website/api/paypal/create_order.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enrollment_id: enroll.enrollment_id }) });
                const data2 = await r.json();
                if (!data2.orderID) throw new Error('Failed to create PayPal order');
                return data2.orderID;
            },
            onApprove: async function(data, actions) {
                const r = await fetch('/website/api/paypal/capture.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderID: data.orderID, enrollment_id: window._enrollmentId }) });
                const res = await r.json();
                if (res.success) {
                    alert('Payment complete! Thank you.');
                    window.location.href = '/website/course.php?course_id=' + courseId;
                } else {
                    alert('Payment verification failed: ' + (res.message || ''));
                }
            }
        }).render('#paypalButtonContainer');
    };
    document.head.appendChild(script);
}

// Paystack flow
async function initPaystack(enrollmentId) {
    const r = await fetch('/website/api/paystack/init.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enrollment_id: enrollmentId }) });
    const data = await r.json();
    if (!data.success) { alert('Paystack init failed: ' + (data.message || '')); return; }
    if (typeof PaystackPop === 'undefined' || !window.PaystackPop) {
        alert('Paystack SDK failed to load.');
        return;
    }
    const handler = PaystackPop.setup({
        key: data.public_key,
        email: data.customer_email,
        amount: data.amount * 100, // Paystack expects kobo
        ref: data.reference,
        onClose: function() { alert('Payment window closed'); },
        callback: async function(response) {
            // verify server-side
            const v = await fetch('/website/api/paystack/verify.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ reference: response.reference, enrollment_id: enrollmentId }) });
            const vr = await v.json();
            if (vr.success) { alert('Payment successful'); window.location.reload(); }
            else { alert('Payment verification failed'); }
        }
    });
    handler.openIframe();
}

// Bind paystack button
document.getElementById('paystackPay').addEventListener('click', async function() {
    // Check configuration key
    if (!PAYSTACK_PUBLIC_KEY || PAYSTACK_PUBLIC_KEY.indexOf('your-paystack') !== -1) { alert('Paystack is not configured on this site.'); return; }

    const firstName = document.getElementById('guestFirstName').value;
    const lastName = document.getElementById('guestLastName').value;
    const email = document.getElementById('guestEmail').value;
    const password = document.getElementById('guestPassword').value;
    const passwordConfirm = document.getElementById('guestPasswordConfirm').value;
    if (password && password !== passwordConfirm) { alert('Passwords do not match'); return; }
    const enroll = await createEnrollment(firstName, lastName, email, password);
    if (!enroll.success) { alert('Failed to create enrollment: ' + enroll.message); return; }
    // load paystack script then init
    const s = document.createElement('script');
    s.src = 'https://js.paystack.co/v1/inline.js';
    s.onload = () => initPaystack(enroll.enrollment_id);
    document.head.appendChild(s);
});

// PayPal buttons will be initialized when the modal is shown (to ensure proper rendering).
</script>
</body>
</html>