<?php
include "user/db.php";
session_start();

if (!isset($_GET['id'])) {
    die("Course not found.");
}

$id = intval($_GET['id']);

/* ================= FETCH COURSE ================= */
$stmt = $conn->prepare("SELECT * FROM courses WHERE id=? LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$course = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$course) {
    die("Course not found.");
}

/* ================= COVER IMAGE ================= */
$coverFile = 'uploads/covers/' . basename($course['cover']);
$absoluteCover = __DIR__ . '/' . $coverFile;
$cover = file_exists($absoluteCover)
    ? $coverFile
    : 'uploads/covers/default-course.jpg';

/* ================= HANDLE OUTLINE DOWNLOAD ================= */
$download_error = '';

if (isset($_POST['request_outline'])) {

    $name  = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);

    if (!$name || !$email || !$phone) {
        $download_error = "All fields are required.";
    } else {

        /* ---- Check duplicate email per course ---- */
        $check = $conn->prepare("
            SELECT id FROM course_outline_downloads
            WHERE course_id=? AND email=? LIMIT 1
        ");
        $check->bind_param("is", $id, $email);
        $check->execute();
        $exists = $check->get_result()->fetch_assoc();
        $check->close();

        if ($exists) {
            $download_error = "You have already downloaded this course outline.";
        } else {

            /* ---- Save record ---- */
            $insert = $conn->prepare("
                INSERT INTO course_outline_downloads
                (course_id, full_name, email, phone)
                VALUES (?,?,?,?)
            ");
            $insert->bind_param("isss", $id, $name, $email, $phone);
            $insert->execute();
            $insert->close();

            /* ---- Serve PDF immediately ---- */
            $outlineFile = basename($course['course_outline_pdf']);
            $outlineRelative = 'uploads/course_outlines/' . $outlineFile;
            $outlineAbsolute = __DIR__ . '/' . $outlineRelative;

            if (!file_exists($outlineAbsolute)) {
                die("Outline file not found on server.");
            }

            header("Content-Type: application/pdf");
            header("Content-Disposition: attachment; filename=\"$outlineFile\"");
            header("Content-Length: " . filesize($outlineAbsolute));
            header("Cache-Control: no-store, no-cache, must-revalidate");
            header("Pragma: no-cache");

            readfile($outlineAbsolute);
            exit;
        }
    }
}

/* ================= DESCRIPTION SHORTEN ================= */
$fullDescription  = strip_tags($course['description']);
$shortDescription = mb_strimwidth($fullDescription, 0, 320, "...");
$price = floatval($course['price']);
$pay_text = ($price > 0) ? "Pay and Enroll ₦" . number_format($price, 2) : "Enroll for Free";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= htmlspecialchars($course['title']); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<style>
:root{
    --primary:#0f172a;
    --accent:#309992;
    --radius:16px;
}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:Inter,system-ui,sans-serif;background:#0f172a;color:#1e293b}
.course-wrapper{max-width:1000px;margin:30px auto;padding:20px}
.course-card{background:#fff;border-radius:var(--radius);overflow:hidden}
.course-cover{height:380px;display:flex;align-items:center;justify-content:center;background:#020617}
.course-cover img{max-width:100%;max-height:100%;object-fit:contain}
.course-content{padding:25px}
.tutor{color:#64748b;margin-bottom:15px}
.description{line-height:1.7;color:#334155}
.actions{display:flex;flex-wrap:wrap;gap:15px;margin-top:25px}
.btn{padding:14px 26px;border-radius:50px;font-size:16px;text-decoration:none;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--primary);color:#fff}
.btn-secondary{border:1px solid var(--primary);color:var(--primary)}
.btn-download{background:#e2e8f0;color:#020617}
.read-more-btn{color:var(--accent);cursor:pointer;font-weight:600}

.modal{
    position:fixed;inset:0;
    background:rgba(2,6,23,.85);
    display:none;align-items:center;justify-content:center;
}
.modal-content{
    background:#fff;padding:25px;border-radius:16px;
    max-width:420px;width:100%;
}
.modal-content input{
    width:100%;padding:12px;margin-bottom:12px
}
.modal-content button{
    width:100%;padding:12px;
    background:var(--primary);color:#fff;border:none;border-radius:40px
}
</style>
</head>

<body>

<div class="course-wrapper">
<div class="course-card">

<div class="course-cover">
    <img src="<?= $cover ?>" alt="">
</div>

<div class="course-content">
<h1><?= htmlspecialchars($course['title']) ?></h1>
<div class="tutor">Tutor: <?= htmlspecialchars($course['tutor']) ?></div>

<div class="description" id="desc">
    <?= nl2br(htmlspecialchars($shortDescription)) ?>
    <span class="read-more-btn" onclick="toggleDesc()">Read more</span>
</div>

<div class="actions">
<?php if($course['course_outline_pdf']): ?>
<button class="btn btn-download" onclick="openModal()">
    <i class="fa fa-file-pdf"></i> Download Course Outline
</button>
<?php endif; ?>

<a href="<?= isset($_SESSION['user_id']) ? "user/dashboard.php?pay_course={$course['id']}" : "login.php" ?>"
   class="btn btn-primary"><?= $pay_text ?></a>

<a href="index.php" class="btn btn-secondary">Back</a>
</div>
</div>

</div>
</div>

<!-- MODAL -->
<div class="modal" id="outlineModal">
<div class="modal-content">
<h3>Download Course Outline</h3>

<?php if($download_error): ?>
<p style="color:red"><?= htmlspecialchars($download_error) ?></p>
<?php endif; ?>

<form method="post">
<input name="full_name" placeholder="Full Name" required>
<input name="email" type="email" placeholder="Email Address" required>
<input name="phone" placeholder="Phone Number" required>
<button name="request_outline">Download</button>
</form>
</div>
</div>

<script>
const fullText  = <?= json_encode(nl2br(htmlspecialchars($fullDescription))) ?>;
const shortText = <?= json_encode(nl2br(htmlspecialchars($shortDescription))) ?>;
let expanded=false;

function toggleDesc(){
    const el=document.getElementById('desc');
    expanded=!expanded;
    el.innerHTML = expanded
        ? fullText+' <span class="read-more-btn" onclick="toggleDesc()">Read less</span>'
        : shortText+' <span class="read-more-btn" onclick="toggleDesc()">Read more</span>';
}
function openModal(){
    document.getElementById('outlineModal').style.display='flex';
}
</script>

</body>
<footer>
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <p>
          © 2025 Activ8Hub — Digital Skills Training Hub, Awka.<br>
          Designed & Developed by Activ8Hub Team.
        </p>
      </div>
    </div>
  </div>
</footer>
</html>
