<?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/capgemini-theme.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 */
        .utility-bar, .cap-header, .scroll-progress { z-index: 1010; }
    </style>
</head>
<body>
    <div class="scroll-progress" id="scrollProgress"></div>

    <!-- Utility Bar - Top -->
    <div class="utility-bar">
        <div class="container">
            <div class="utility-links">
                <a href="mailto:study@smartthinkllc.com"><i class="fas fa-envelope"></i><span>study@smartthinkllc.com</span></a>
                <a href="tel:+12027907745"><i class="fas fa-phone"></i><span>(+1) 202-790-7745</span></a>
            </div>
            <div class="utility-right">
                <div class="global-dropdown" id="globalDropdown">
                    <button class="global-dropdown-toggle" onclick="toggleGlobalDropdown()">
                        <i class="fas fa-globe"></i>
                        <span>Global | EN</span>
                        <i class="fas fa-chevron-down" style="font-size: 0.7em;"></i>
                    </button>
                    <div class="global-dropdown-menu"><!-- same as index.php --></div>
                </div>
                <div class="utility-item">
                    <i class="fas fa-search"></i>
                    <span>Search</span>
                </div>
                <div class="theme-toggle" onclick="toggleTheme()">
                    <i class="fas fa-moon" id="themeIcon"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Capgemini-Style Header -->
    <header class="cap-header">
        <div class="container">
            <a class="cap-brand" href="index.php">
                <img src="../assets/images/logo.jpeg" alt="SmartThink" class="cap-logo">
                <span class="cap-brand-text">SmartThink</span>
            </a>
            
            <nav>
                <ul class="cap-nav">
                    <li class="cap-nav-item"><a class="cap-nav-link" href="index.php">Home</a></li>
                    <li class="cap-nav-item"><a class="cap-nav-link" href="about.php">About us</a></li>
                    <li class="cap-nav-item has-dropdown">
                        <a class="cap-nav-link" href="services.php">
                            Services
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="cap-dropdown">
                            <a class="cap-dropdown-link" href="advisory_it_solutions.php">Advisory and IT Solutions</a>
                            <a class="cap-dropdown-link" href="training.php">Training</a>
                            <a class="cap-dropdown-link" href="recruitment.php">Recruitment</a>
                        </div>
                    </li>
                    <li class="cap-nav-item"><a class="cap-nav-link active" href="courses.php">Courses</a></li>
                    <li class="cap-nav-item"><a class="cap-nav-link" href="careers.php">Careers</a></li>
                    <li class="cap-nav-item has-dropdown">
                        <a class="cap-nav-link" href="training.php">
                            Training
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="cap-dropdown">
                            <a class="cap-dropdown-link" href="cyber_grc.php">Cyber GRC</a>
                            <a class="cap-dropdown-link" href="ai_governance.php">AI Governance</a>
                        </div>
                    </li>
                </ul>
            </nav>

            <div class="d-flex align-items-center">
                <div class="cap-auth ms-4">
                    <a href="../lms/login.php" class="btn-cap-login">Login</a>
                    <a href="../lms/register.php" class="btn-cap-register">Register</a>
                </div>
                <button class="navbar-toggler d-lg-none ms-3" type="button" style="background: transparent; border: none; color: white;" onclick="document.querySelector('.cap-nav').classList.toggle('open')">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
        </div>
    </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="cap-footer">
        <div class="container">
            <div class="footer-main">
                <div class="row">
                    <div class="col-lg-4">
                        <div class="footer-brand-cap">
                            <img src="../assets/images/logo.jpeg" alt="SmartThink" class="footer-logo-cap">
                            <p><?php sc_html('home', 'footer_about', 'Empowering learners globally with cutting-edge educational technology and world-class content.', $region); ?></p>
                            <div class="footer-social-cap">
                                <a href="#"><i class="fab fa-linkedin"></i></a>
                                <a href="#"><i class="fab fa-twitter"></i></a>
                                <a href="#"><i class="fab fa-facebook"></i></a>
                                <a href="#"><i class="fab fa-youtube"></i></a>
                                <a href="#"><i class="fab fa-instagram"></i></a>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-2 col-md-4">
                        <div class="footer-links-cap">
                            <h4>About us</h4>
                            <ul>
                                <li><a href="about.php">Who we are</a></li>
                                <li><a href="leadership.php">Leadership</a></li>
                                <li><a href="sustainability.php">Sustainability</a></li>
                                <li><a href="awards.php">Awards</a></li>
                            </ul>
                        </div>
                    </div>

                    <div class="col-lg-2 col-md-4">
                        <div class="footer-links-cap">
                            <h4>Services</h4>
                            <ul>
                                <li><a href="training.php">Training</a></li>
                                <li><a href="consulting.php">Consulting</a></li>
                                <li><a href="recruitment.php">Recruitment</a></li>
                                <li><a href="support.php">Support</a></li>
                            </ul>
                        </div>
                    </div>

                    <div class="col-lg-2 col-md-4">
                        <div class="footer-links-cap">
                            <h4>Insights</h4>
                            <ul>
                                <li><a href="blog.php">Blog</a></li>
                                <li><a href="research.php">Research</a></li>
                                <li><a href="case-studies.php">Case studies</a></li>
                                <li><a href="events.php">Events</a></li>
                            </ul>
                        </div>
                    </div>

                    <div class="col-lg-2 col-md-4">
                        <div class="footer-links-cap">
                            <h4>Careers</h4>
                            <ul>
                                <li><a href="jobs.php">Search jobs</a></li>
                                <li><a href="culture.php">Our culture</a></li>
                                <li><a href="students.php">Students</a></li>
                                <li><a href="professionals.php">Professionals</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <div class="footer-bottom-cap">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <p class="copyright-cap"> 2026 SmartThink. All rights reserved.</p>
                    </div>
                    <div class="col-md-6">
                        <div class="footer-bottom-links-cap">
                            <a href="privacy-policy.php">Data Privacy Policy</a>
                            <a href="training-agreement.php">Training Non-Compete &amp; Materials</a>
                            <a href="payment-policy.php">Non-Refundable Payment Policy</a>
                            <a href="sitemap.php">Sitemap</a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="footer-newsletter">
                <div class="row align-items-center">
                    <div class="col-md-6 mb-3 mb-md-0">
                        <h4>Stay ahead in cybersecurity</h4>
                        <p>Get updates on new courses, insights, and security trends straight to your inbox.</p>
                    </div>
                    <div class="col-md-6">
                        <form class="footer-newsletter-form" action="#" method="post">
                            <input type="email" name="newsletter_email" placeholder="Work email address" required>
                            <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>
    <script src="../assets/js/modern-interactions.js"></script>
    <script src="../assets/js/global-theme.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 class="mt-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="agreeTerms">
                    <label class="form-check-label" for="agreeTerms">
                        I agree to the training agreement and terms for this course.
                    </label>
                </div>
            </div>

            <div id="paymentMethods">
                <h5>Pay with</h5>
                <div id="paypalButtonContainer"></div>
                <button id="paystackPay" class="btn btn-outline-primary mt-3 me-2">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();
}

async function signAgreement(enrollmentId, fullName, email) {
    const res = await fetch('/website/api/enrollment_agreement_sign.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enrollment_id: enrollmentId, full_name: fullName, email: email })
    });
    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 agree = document.getElementById('agreeTerms');
                if (agree && !agree.checked) {
                    document.getElementById('checkoutErrors').innerText = 'You must agree to the training terms before proceeding.';
                    document.getElementById('checkoutErrors').style.display = 'block';
                    throw new Error('Agreement not accepted');
                }
                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 fullName = (firstName + ' ' + lastName).trim() || email;
                const agreement = await signAgreement(enroll.enrollment_id, fullName, email);
                if (!agreement.success) {
                    document.getElementById('checkoutErrors').innerText = agreement.message || 'Failed to sign agreement';
                    document.getElementById('checkoutErrors').style.display = 'block';
                    throw new Error('Agreement signing failed');
                }
                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 agree = document.getElementById('agreeTerms');
    if (agree && !agree.checked) { alert('You must agree to the training terms before proceeding.'); return; }
    const enroll = await createEnrollment(firstName, lastName, email, password);
    if (!enroll.success) { alert('Failed to create enrollment: ' + enroll.message); return; }
    const fullName = (firstName + ' ' + lastName).trim() || email;
    const agreement = await signAgreement(enroll.enrollment_id, fullName, email);
    if (!agreement.success) { alert('Failed to sign agreement: ' + (agreement.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);
});
</script>
</body>
</html>
