<?php
session_start();
include('../../../connect.php');
include('includes/send_email.php'); // Include the email sending function

// Email notification template for new study material
function getStudyMaterialEmailTemplate($studentName, $courseName, $courseDesc, $materialName) {
    $template = '
<html>
<head>
    <title>New Study Material Uploaded</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            color: #333;
        }
        .container {
            max-width: 600px;
            margin: 20px auto;
            padding: 30px;
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid #ddd;
        }
        h1 {
            font-size: 26px;
            color: #0056b3;
            margin-bottom: 20px;
            border-bottom: 2px solid #0056b3;
            padding-bottom: 10px;
        }
        p {
            font-size: 16px;
            line-height: 1.6;
            margin-bottom: 20px;
        }
        .highlight {
            color: #0056b3;
            font-weight: bold;
        }
        .cta-button {
            display: inline-block;
            padding: 12px 20px;
            margin-top: 20px;
            background-color: #0056b3;
            color: #ffffff;
            text-align: center;
            border-radius: 6px;
            text-decoration: none;
            font-weight: bold;
            font-size: 16px;
        }
        .cta-button:hover {
            background-color: #004494;
        }
        .signature {
            margin-top: 30px;
            text-align: left;
            font-style: italic;
            font-size: 14px;
            color: #666;
        }
        .footer {
            margin-top: 30px;
            font-size: 12px;
            text-align: center;
            color: #999;
            border-top: 1px solid #ddd;
            padding-top: 10px;
        }
        .footer a {
            color: #0056b3;
            text-decoration: none;
        }
        .footer a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>New Study Material Uploaded</h1>
        <p>Dear <span class="highlight">' . $studentName . '</span>,</p>
        <p>New study material has been uploaded for your course <strong class="highlight">' . $courseName . ' ' . $courseDesc . '</strong>.</p>
        <p><strong>Material Name:</strong> ' . $materialName . '</p>
        <p>To access the material, please log in to your dashboard and navigate to the study materials section.</p>
        <p><a href="https://portal.aivtic.org.ng" class="cta-button">Access Your Dashboard</a></p>
        <div class="signature">
            <p>Sincerely,</p>
            <p>A-I Vocational Training Institute of Cybersecurity</p>
            <p>Course Instructor</p>
        </div>
        <div class="footer">
            <p>&copy; ' . date('Y') . ' A-I Vocational Training Institute of Cybersecurity. All rights reserved.</p>
            <p><a href="https://aivtic.org.ng">Visit our website</a> | <a href="mailto:support@aivtic.org.ng">Contact Us</a></p>
        </div>
    </div>
</body>
</html>';
    return $template;
}

// Check if instructor is logged in
if (strlen($_SESSION['instructor-username']) == "" || !isset($_SESSION['instructor-username'])) {
    header("Location: logout.php");
    exit();
}

// Handle file upload and email notification
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['courseId']) && isset($_POST['courseDesc']) && isset($_FILES['fileToUpload'])) {
        $courseId = $_POST['courseId'];
        $courseDesc = $_POST['courseDesc'];

        $courseId = mysqli_real_escape_string($conn, $courseId);
        $courseDesc = mysqli_real_escape_string($conn, $courseDesc);

        $materialName = $courseDesc . " ";

        // Allowed file extensions
        $allowedExtensions = array('ZIP', 'PDF', 'PPT', 'PPTX', 'DOC', 'DOCX');
        $fileExtension = strtoupper(pathinfo($_FILES['fileToUpload']['name'], PATHINFO_EXTENSION));

        if ($_FILES['fileToUpload']['error'] == UPLOAD_ERR_OK && in_array($fileExtension, $allowedExtensions)) {
            $uploadDir = "../uploads/";
            $fileName = uniqid() . "_" . basename($_FILES['fileToUpload']['name']);
            $targetPath = $uploadDir . $fileName;

            if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $targetPath)) {
                $materialUrl = $targetPath; // Using the target path as is

                // Insert study material into database
                $sql = "INSERT INTO `study_materials` (`courseId`, `materialName`, `materialType`, `materialUrl`, `uploadDate`) VALUES ('$courseId', '$materialName', ?, '$materialUrl', NOW())";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("s", $fileExtension);

                if ($stmt->execute()) {
                    // Fetch students enrolled in the course
                    $studentsSql = "
                        SELECT a.fullname, a.email, a.normal_email, sc.selected_courses 
                        FROM admission a 
                        INNER JOIN student_courses sc ON a.email = sc.email 
                        WHERE FIND_IN_SET('$courseName', sc.selected_courses) AND a.Admission_Status = 'Admitted'";
                    $result = $conn->query($studentsSql);

                    if ($result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            $studentEmail = $row['normal_email'];
                            $studentName = $row['fullname'];

                            // Prepare email subject and message
                            $subject = "New Study Material Uploaded for $courseDesc";
                            $message = getStudyMaterialEmailTemplate($studentName, $courseDesc, '', $materialName);

                            // Send email
                            $sendEmailResult = sendEmail($studentEmail, $subject, $message);
                            if ($sendEmailResult !== true) {
                                echo "<script>alert('Failed to send email to $studentEmail.');</script>";
                            }
                        }
                    }

                    echo "<script>alert('Study material uploaded successfully.'); window.location.href='managematerials.php';</script>";
                } else {
                    echo "<script>alert('Error: " . $stmt->error . "');</script>";
                }
                $stmt->close();
            } else {
                echo "<script>alert('Error uploading file.');</script>";
            }
        } else {
            echo "<script>alert('Error: Please upload a valid file (ZIP, PDF, PPT, PPTX, DOC, DOCX).');</script>";
        }
    } else {
        echo "<script>alert('Missing parameters.');</script>";
    }
} else {
    echo "<script>alert('Invalid request.');</script>";
}

mysqli_close($conn);
?>
