<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
include "back.php";

include "../user/db.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../user/PHPMailer/src/PHPMailer.php';
require '../user/PHPMailer/src/SMTP.php';
require '../user/PHPMailer/src/Exception.php';

// Only admin can access
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

// Fetch courses
$courses = $conn->query("SELECT id, title FROM courses");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $course_id = $_POST['course_id'];
    $title = trim($_POST['title']);
    $message = trim($_POST['message']);
    $certificate_path = null;

    // === Handle certificate upload safely ===
    if (isset($_FILES['certificate']) && $_FILES['certificate']['error'] === 0) {
        $uploadDir = __DIR__ . '/../certificates/';  // absolute path

        // Create folder if missing
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        // Allowed file types
        $allowedTypes = [
            'application/pdf' => '.pdf',
            'image/jpeg' => '.jpg',
            'image/png' => '.png'
        ];

        $fileTmp = $_FILES['certificate']['tmp_name'];
        $fileType = mime_content_type($fileTmp);

        if (!array_key_exists($fileType, $allowedTypes)) {
            die("Invalid file type. Only PDF, JPG, and PNG allowed.");
        }

        // Unique filename
        $extension = $allowedTypes[$fileType];
        $filename = time() . '_' . uniqid() . $extension;
        $targetFile = $uploadDir . $filename;

        if (move_uploaded_file($fileTmp, $targetFile)) {
            $certificate_path = $filename; // store just filename in DB
        } else {
            die("Failed to upload certificate. Check folder permissions.");
        }
    }

    // === Insert update into DB ===
    $stmt = $conn->prepare("
        INSERT INTO course_updates (course_id, title, message, certificate)
        VALUES (?, ?, ?, ?)
    ");
    $stmt->bind_param("isss", $course_id, $title, $message, $certificate_path);
    $stmt->execute();

    // === Fetch users who purchased this course ===
    $users = $conn->prepare("
        SELECT u.email, p.fullname
        FROM user_payments p
        INNER JOIN users u ON p.user_id = u.id
        WHERE p.course_id = ?
    ");
    $users->bind_param("i", $course_id);
    $users->execute();
    $result = $users->get_result();

    // === Send email via PHPMailer ===
    while ($row = $result->fetch_assoc()) {
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'twinklegoodluck@gmail.com';
            $mail->Password = 'nnlqxkuftyxnekuv'; // use app password
            $mail->SMTPSecure = 'tls';
            $mail->Port = 587;

            $mail->setFrom('no-reply@Activ8hub.com', 'No-Code School');
            $mail->addAddress($row['email'], $row['fullname']);

            // Attach certificate if exists
            if ($certificate_path) {
                $mail->addAttachment($targetFile, $_FILES['certificate']['name']);
            }

            $mail->isHTML(true);
            $mail->Subject = "New Update for Your Course";
            $mail->Body    = "
                <h2>Hello {$row['fullname']},</h2>
                <p>A new update has been added to your course.</p>
                <h3>{$title}</h3>
                <p>{$message}</p>
                <p><strong>Log in to your dashboard to view details.</strong></p>
                <p>Best regards,<br>No-Code School Team</p>
            ";

            $mail->send();
        } catch (Exception $e) {
            // Optionally log errors
            error_log("Email to {$row['email']} failed: " . $mail->ErrorInfo);
        }
    }

    $success = true;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Post Course Update</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root {
    --primary-color: #5d5dff;
    --bg: #f5f7fb;
    --card: #fff;
    --text: #222;
    --muted: #666;
    --border: #ddd;
}
body.dark {
    --bg: #1a1a2e;
    --card: #2a2a44;
    --text: #fff;
    --muted: #aaa;
    --border: #444;
}
body { margin:0; background:var(--bg); font-family:Segoe UI; padding:20px; transition:0.3s; }
.card { background:var(--card); max-width:700px; margin:auto; padding:25px; border-radius:15px; box-shadow:0 5px 20px rgba(0,0,0,0.2); transition:0.3s; }
h2 { color: var(--primary-color); text-align:center; }
input, select, textarea { width:100%; padding:12px; margin-top:10px; border-radius:8px; border:1px solid var(--border); background:var(--bg); color:var(--text); }
button { margin-top:15px; background:rgb(26,26,46); color:#fff; border:none; padding:12px; border-radius:8px; cursor:pointer; width:100%; font-size:16px; display:flex; align-items:center; justify-content:center; gap:5px; }
.success { background:#dcfce7; padding:10px; margin-bottom:15px; border-radius:8px; color:#166534; text-align:center; }
.topbar { display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; flex-wrap:wrap; gap:10px; }
.topbar button { width:auto; padding:8px 14px; font-size:14px; display:flex; align-items:center; gap:5px; }
@media(max-width:768px){.card{padding:15px}}
</style>
</head>
<body>

<div class="topbar" >
    <button onclick="history.back()"><i class="fas fa-arrow-left"></i> Back</button>
    <button onclick="toggleTheme()"><i class="fas fa-moon"style="background-color:rgb(26,26,46);"></i> </button>
</div>

<div class="card">
    <h2 style="color:rgb(26,26,46);">Post Course Update</h2>
    <?php if (!empty($success)): ?>
        <div class="success">Update sent successfully </div>
    <?php endif; ?>
    <form method="POST" enctype="multipart/form-data">
        <label>Course</label>
        <select name="course_id" required>
            <?php while ($c = $courses->fetch_assoc()): ?>
                <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['title']) ?></option>
            <?php endwhile; ?>
        </select>

        <label>Update Title</label>
        <input type="text" name="title" required>

        <label>Message</label>
        <textarea name="message" rows="6" required></textarea>

        <label>Attach file(optional)</label>
        <input type="file" name="certificate" accept=".pdf,.jpg,.png">

        <button type="submit"><i class="fas fa-paper-plane" style="color:rgb(26,26,46);"></i style="color:rgb(26,26,46);"> Publish Update</button>
    </form>
</div>

<script>
function toggleTheme(){
    document.body.classList.toggle('dark');
}
</script>

</body>
</html>
<?php
include "footer.php";
?>
