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

requireLogin();
$user = getCurrentUser();
$courseModel = new Course();
$db = Database::getInstance();

$errors = [];
$success = getFlashMessage('success');
$errorFlash = getFlashMessage('error');
if ($errorFlash) {
    $errors[] = $errorFlash;
}

// Handle actions (enroll)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'enroll') {
    if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
        setFlashMessage('error', 'Only students can enroll in courses.');
        header('Location: courses.php');
        exit;
    }

    $courseId = (int)($_POST['course_id'] ?? 0);

    // Determine if course is free or paid
    $courseRow = $db->get('SELECT price FROM courses WHERE id = ?', [$courseId]);
    if (!$courseRow) {
        $errors[] = 'Course not found.';
    } else {
        $price = (float)($courseRow['price'] ?? 0);

        // For paid courses, route to checkout so payment can be completed first
        if ($price > 0) {
            header('Location: ' . APP_URL . '/lms/course_checkout.php?course_id=' . $courseId);
            exit;
        }

        // Free courses can be enrolled immediately
        try {
            $courseModel->enroll($courseId, $user['id']);
            setFlashMessage('success', 'Enrolled successfully.');
            header('Location: courses.php');
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

// Filters
$filters = [];
if (!empty($_GET['category_id'])) {
    $filters['category_id'] = (int)$_GET['category_id'];
}
if (!empty($_GET['level'])) {
    $filters['level'] = trim($_GET['level']);
}
if (!empty($_GET['search'])) {
    $filters['search'] = trim($_GET['search']);
}
if (isset($_GET['free_only']) && $_GET['free_only']) {
    $filters['free_only'] = true;
}
if (!empty($_GET['sort'])) {
    $filters['sort'] = trim($_GET['sort']);
}

// Apply region filter for students (optional) - Course::getCourses supports region
if (isset($_SESSION['region'])) {
    $filters['region'] = $_SESSION['region'];
}

// Get data
$categories = $db->getAll("SELECT id, name FROM categories WHERE is_active = 1 ORDER BY name");

// Pagination
$perPage = 12;
$page = max(1, (int)($_GET['page'] ?? 1));
$total = $courseModel->countCourses($filters);
$totalPages = max(1, (int)ceil($total / $perPage));
$offset = ($page - 1) * $perPage;

$courses = $courseModel->getCourses($filters, $perPage, $offset);

// If instructor requested their own courses, override with instructor-specific list
if (!empty($_GET['mine']) && hasRole('instructor')) {
    $courses = $courseModel->getInstructorCourses($user['id']);
    $total = count($courses);
    $totalPages = max(1, (int)ceil($total / $perPage));
}

// If a single course is requested, show course detail and lessons
if (!empty($_GET['course_id'])) {
    $courseId = (int)$_GET['course_id'];
    $course = $courseModel->getById($courseId);
    if (!$course) {
        setFlashMessage('error', 'Course not found.');
        header('Location: ' . APP_URL . '/lms/courses.php');
        exit;
    }

    $enrollmentAgreement = null;
    if (isset($_SESSION['role']) && $_SESSION['role'] === 'student') {
        $enrollmentAgreement = $db->get(
            "SELECT ce.id AS enrollment_id, a.id AS agreement_id
               FROM course_enrollments ce
          LEFT JOIN course_enrollment_agreements a ON a.enrollment_id = ce.id AND a.status = 'signed'
              WHERE ce.course_id = ? AND ce.student_id = ?
           ORDER BY ce.enrollment_date DESC
              LIMIT 1",
            [$courseId, $user['id']]
        );
    }

    $lessons = $courseModel->getLessons($courseId);

    // Upcoming live Zoom sessions for this course
    $upcomingSessions = $db->getAll(
        "SELECT id, title, zoom_start_time, zoom_join_url, content_url
           FROM course_lessons
          WHERE course_id = ?
            AND content_type = 'live_session'
            AND zoom_start_time IS NOT NULL
            AND zoom_start_time >= NOW()
            AND is_published = 1
       ORDER BY zoom_start_time ASC
          LIMIT 10",
        [$courseId]
    );

    // Past Zoom recordings (video lessons created from Zoom webhook)
    $recordingLessons = $db->getAll(
        "SELECT id, title, content_url, created_at
           FROM course_lessons
          WHERE course_id = ?
            AND content_type = 'video'
            AND content_url IS NOT NULL
            AND content_url LIKE '%zoom.us/%'
            AND is_published = 1
       ORDER BY created_at DESC
          LIMIT 10",
        [$courseId]
    );

    $studentInstallments = [];
    if (isset($_SESSION['role']) && $_SESSION['role'] === 'student') {
        $studentInstallments = $db->getAll(
            "SELECT ei.*
               FROM enrollment_installments ei
               JOIN course_enrollments ce ON ei.enrollment_id = ce.id
              WHERE ce.course_id = ? AND ce.student_id = ?
           ORDER BY ei.due_date ASC",
            [$courseId, $user['id']]
        );
    }

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

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h4 mb-0"><?php echo htmlspecialchars($course['title']); ?></h1>
            <p class="text-muted mb-0"><?php echo htmlspecialchars($course['short_description'] ?? ''); ?></p>
        </div>
        <div>
            <?php if (hasRole('instructor') && $course['instructor_id'] === $user['id']): ?>
                <a href="<?php echo APP_URL; ?>/lms/lessons_edit.php?course_id=<?php echo (int)$courseId; ?>" class="btn btn-primary">New Lesson</a>
                <a href="<?php echo APP_URL; ?>/lms/courses_edit.php?id=<?php echo (int)$courseId; ?>" class="btn btn-outline-secondary ms-2">Edit Course</a>
            <?php endif; ?>
            <?php if (isset($_SESSION['role']) && $_SESSION['role'] === 'student' && $enrollmentAgreement && !empty($enrollmentAgreement['agreement_id'])): ?>
                <a href="<?php echo APP_URL; ?>/lms/view_agreement.php?enrollment_id=<?php echo (int)$enrollmentAgreement['enrollment_id']; ?>" class="btn btn-outline-secondary ms-2">View Agreement</a>
            <?php endif; ?>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8">
            <div class="card mb-4">
                <div class="card-body">
                    <?php echo nl2br(htmlspecialchars($course['description'])); ?>
                </div>
            </div>

            <div class="card" id="course-lessons">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h5 class="m-0">Lessons</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($lessons)): ?>
                        <p class="text-muted">No lessons yet.</p>
                    <?php else: ?>
                        <ul class="list-group">
                            <?php foreach ($lessons as $l): ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <div>
                                        <a href="<?php echo APP_URL; ?>/lms/lesson.php?id=<?php echo (int)$l['id']; ?>"><?php echo htmlspecialchars($l['title']); ?></a>
                                        <div class="text-muted small"><?php echo htmlspecialchars($l['content_type']); ?></div>
                                    </div>
                                    <div>
                                        <?php if (hasRole('instructor') && $course['instructor_id'] === $user['id']): ?>
                                            <a class="btn btn-sm btn-outline-secondary" href="<?php echo APP_URL; ?>/lms/lessons_edit.php?id=<?php echo (int)$l['id']; ?>">Edit</a>
                                        <?php endif; ?>
                                        <?php if ($l['content_type'] === 'quiz'): ?>
                                            <a class="btn btn-sm btn-primary ms-2" href="<?php echo APP_URL; ?>/lms/assessments.php?lesson_id=<?php echo (int)$l['id']; ?>">Open Quiz</a>
                                        <?php endif; ?>
                                    </div>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <?php if (isset($_SESSION['role']) && $_SESSION['role'] === 'student' && !empty($studentInstallments)): ?>
                <div class="card mb-3">
                    <div class="card-header">
                        <h6 class="m-0">Payment Schedule</h6>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled mb-0 small">
                            <?php foreach ($studentInstallments as $inst): ?>
                                <?php
                                    $dueTs = !empty($inst['due_date']) ? strtotime($inst['due_date']) : null;
                                    $daysLeft = null;
                                    if ($dueTs) {
                                        $daysLeft = (int) floor(($dueTs - time()) / 86400);
                                    }
                                ?>
                                <li class="mb-2">
                                    <div class="fw-semibold">
                                        Installment <?php echo (int)($inst['installment_no'] ?? 1); ?>:
                                        <?php echo htmlspecialchars(number_format((float)($inst['amount'] ?? 0.0), 2)); ?>
                                        <?php echo htmlspecialchars($inst['currency'] ?? 'USD'); ?>
                                    </div>
                                    <?php if ($dueTs): ?>
                                        <div class="text-muted">
                                            Due: <?php echo htmlspecialchars(date('Y-m-d H:i', $dueTs)); ?>
                                            <?php if ($daysLeft !== null && $daysLeft >= 0): ?>
                                                (in <?php echo $daysLeft; ?> day<?php echo $daysLeft === 1 ? '' : 's'; ?>)
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="text-muted">
                                        Status: <?php echo htmlspecialchars($inst['status'] ?? 'pending'); ?>
                                    </div>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            <?php endif; ?>
            <div class="card mb-3">
                <div class="card-header">
                    <h6 class="m-0">Upcoming Sessions</h6>
                </div>
                <div class="card-body">
                    <?php if (!empty($upcomingSessions)): ?>
                        <ul class="list-unstyled mb-0 small">
                            <?php foreach ($upcomingSessions as $s): ?>
                                <?php
                                    $start = $s['zoom_start_time'] ?? null;
                                    $joinUrl = $s['zoom_join_url'] ?? ($s['content_url'] ?? null);
                                    $startTs = $start ? strtotime($start) : null;
                                    $now = time();
                                    $isToday = $startTs ? (date('Y-m-d', $startTs) === date('Y-m-d')) : false;
                                    $isLiveNow = $startTs ? (abs($now - $startTs) <= 1800) : false; // within 30 minutes of start
                                ?>
                                <li class="mb-2">
                                    <div class="d-flex align-items-center mb-1">
                                        <?php if ($isLiveNow): ?>
                                            <span class="badge bg-danger me-2">LIVE NOW</span>
                                        <?php elseif ($isToday): ?>
                                            <span class="badge bg-success me-2">Today</span>
                                        <?php endif; ?>
                                        <div class="fw-semibold mb-0"><?php echo htmlspecialchars($s['title']); ?></div>
                                    </div>
                                    <?php if ($startTs): ?>
                                        <div class="text-muted">
                                            <?php
                                                $timeLabel = $isToday ? 'Today, ' . date('H:i', $startTs) : date('Y-m-d H:i', $startTs);
                                                echo htmlspecialchars($timeLabel);
                                            ?>
                                            (<?php echo date_default_timezone_get(); ?>)
                                        </div>
                                    <?php endif; ?>
                                    <?php if ($joinUrl): ?>
                                        <a href="<?php echo htmlspecialchars($joinUrl); ?>" target="_blank" class="btn btn-sm btn-primary mt-1">Join Session</a>
                                    <?php endif; ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php else: ?>
                        <p class="text-muted mb-0">No upcoming live Zoom sessions scheduled for this course yet.</p>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card mb-3">
                <div class="card-header">
                    <h6 class="m-0">Past Sessions (Recordings)</h6>
                </div>
                <div class="card-body">
                    <?php if (!empty($recordingLessons)): ?>
                        <ul class="list-unstyled mb-0 small">
                            <?php foreach ($recordingLessons as $r): ?>
                                <li class="mb-2">
                                    <a href="<?php echo APP_URL; ?>/lms/lesson.php?id=<?php echo (int)$r['id']; ?>" class="fw-semibold d-block"><?php echo htmlspecialchars($r['title']); ?></a>
                                    <?php if (!empty($r['created_at'])): ?>
                                        <div class="text-muted"><?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($r['created_at']))); ?></div>
                                    <?php endif; ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php else: ?>
                        <p class="text-muted mb-0">No Zoom recordings have been published for this course yet.</p>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card">
                <div class="card-body">
                    <h6>Instructor</h6>
                    <p class="mb-0"><?php echo htmlspecialchars($course['first_name'] . ' ' . $course['last_name']); ?></p>
                </div>
            </div>
        </div>
    </div>

    <?php include __DIR__ . '/includes/footer.php';
    exit;
}

$pageTitle = 'Courses';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h4 mb-0"><?php echo isset($_GET['mine']) && $_GET['mine'] ? 'My Courses' : 'Courses'; ?></h1>
        <p class="text-muted mb-0"><?php echo isset($_GET['mine']) && $_GET['mine'] ? 'Manage your courses.' : 'Browse and enroll in available courses.'; ?></p>
    </div>
    <?php if (hasRole('instructor')): ?>
    <div>
        <a href="<?php echo APP_URL; ?>/lms/courses_edit.php" class="btn btn-primary">New Course</a>
    </div>
    <?php endif; ?>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo htmlspecialchars($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

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

<div class="card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3">
            <div class="col-md-4">
                <input type="search" name="search" class="form-control" placeholder="Search courses..." value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>">
            </div>
            <div class="col-md-3">
                <select name="category_id" class="form-select">
                    <option value="">All categories</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo (int)$cat['id']; ?>" <?php echo (int)($_GET['category_id'] ?? 0) === (int)$cat['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <select name="level" class="form-select">
                    <option value="">Any level</option>
                    <?php foreach (['beginner','intermediate','advanced','all_levels'] as $opt): ?>
                        <option value="<?php echo $opt; ?>" <?php echo (($_GET['level'] ?? '') === $opt) ? 'selected' : ''; ?>><?php echo ucfirst($opt); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <select name="sort" class="form-select">
                    <option value="">Sort</option>
                    <option value="popular" <?php echo (($_GET['sort'] ?? '') === 'popular') ? 'selected' : ''; ?>>Most popular</option>
                    <option value="rating" <?php echo (($_GET['sort'] ?? '') === 'rating') ? 'selected' : ''; ?>>Top rated</option>
                    <option value="newest" <?php echo (($_GET['sort'] ?? '') === 'newest') ? 'selected' : ''; ?>>Newest</option>
                </select>
            </div>

            <div class="col-md-1 text-end">
                <button class="btn btn-primary">Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="row g-3">
    <?php if (!$courses): ?>
        <div class="col-12">
            <div class="card">
                <div class="card-body text-center text-muted">No courses found.</div>
            </div>
        </div>
    <?php else: foreach ($courses as $c): ?>
        <div class="col-12 col-md-6 col-xl-4">
            <div class="card h-100">
                <img src="<?php echo htmlspecialchars($c['thumbnail'] ?? (APP_URL . '/assets/materio/assets/img/illustrations/course.png')); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($c['title']); ?>">
                <div class="card-body d-flex flex-column">
                    <h5 class="card-title mb-1"><?php echo htmlspecialchars($c['title']); ?></h5>
                    <small class="text-muted">By <?php echo htmlspecialchars($c['first_name'] . ' ' . $c['last_name']); ?> &bull; <?php echo htmlspecialchars($c['category_name']); ?></small>
                    <p class="mt-2 mb-0 text-truncate"><?php echo htmlspecialchars(substr($c['short_description'] ?? $c['description'], 0, 120)); ?></p>

                    <div class="mt-2 mb-2">
                        <span class="small text-warning"><i class="ri ri-star-fill"></i> <?php echo round((float)$c['rating'], 1); ?></span>
                    </div>

                    <div class="mt-auto d-flex justify-content-between align-items-center pt-3">
                        <div>
                            <?php if ($c['price'] > 0): ?>
                                <div class="fw-semibold"><?php echo htmlspecialchars(number_format($c['price'], 2)); ?> <?php echo htmlspecialchars($c['currency']); ?></div>
                            <?php else: ?>
                                <div class="fw-semibold">Free</div>
                            <?php endif; ?>
                            <small class="text-muted"><?php echo (int)$c['enrollment_count']; ?> enrolled</small>
                        </div>

                        <div>
                            <?php if (isset($_SESSION['role']) && $_SESSION['role'] === 'student' && $courseModel->isEnrolled($c['id'], $user['id'])): ?>
                                <a href="courses.php?course_id=<?php echo (int)$c['id']; ?>" class="btn btn-outline-secondary btn-sm"><i class="ri ri-arrow-right-line me-1"></i>Go to Course</a>
                            <?php elseif (isset($_SESSION['role']) && $_SESSION['role'] === 'student'): ?>
                                <?php if ((float)$c['price'] > 0): ?>
                                    <a href="<?php echo APP_URL; ?>/lms/course_checkout.php?course_id=<?php echo (int)$c['id']; ?>" class="btn btn-primary btn-sm">
                                        <i class="ri ri-bank-card-line me-1"></i>Enroll &amp; Pay
                                    </a>
                                <?php else: ?>
                                    <form method="post" class="d-inline">
                                        <input type="hidden" name="action" value="enroll">
                                        <input type="hidden" name="course_id" value="<?php echo (int)$c['id']; ?>">
                                        <button class="btn btn-primary btn-sm"><i class="ri ri-book-open-line me-1"></i>Enroll</button>
                                    </form>
                                <?php endif; ?>
                            <?php else: ?>
                                <a href="login.php" class="btn btn-primary btn-sm"><i class="ri ri-login-box-line me-1"></i>Login to Enroll</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach; endif; ?>
</div>

<?php if ($totalPages > 1): ?>
<nav aria-label="Page navigation">
  <ul class="pagination justify-content-center mt-4">
    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
      <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => max(1, $page - 1)])); ?>" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
    <?php for ($p = 1; $p <= $totalPages; $p++): ?>
      <li class="page-item <?php echo $p === $page ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $p])); ?>"><?php echo $p; ?></a></li>
    <?php endfor; ?>
    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
      <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => min($totalPages, $page + 1)])); ?>" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  </ul>
</nav>
<?php endif; ?>

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