<?php
include "../include/config.php";

if (isset($_POST['addCourse'])) {
    $courseName = mysqli_real_escape_string($conn, $_POST['courseName']);
    $semester   = mysqli_real_escape_string($conn, $_POST['semester']);
    $year       = mysqli_real_escape_string($conn, $_POST['year']);

    // Check if programs[] is set
    if (!empty($_POST['programs']) && is_array($_POST['programs'])) {
        $successCount = 0;
        $errorMessages = [];
        
        foreach ($_POST['programs'] as $program) {
            $program = mysqli_real_escape_string($conn, $program);

            // Check if course already exists for this program
            $checkSql = "SELECT * FROM course WHERE course = '$courseName' AND program = '$program'";
            $checkResult = $conn->query($checkSql);
            
            if ($checkResult->num_rows > 0) {
                // Skip this one, it already exists
                $errorMessages[] = "Course '$courseName' already exists for program '$program'";
                continue;
            }

            // Insert new course for this program
            $sql = "INSERT INTO course (course, semester, year, program) 
                    VALUES ('$courseName', '$semester', '$year', '$program')";
            
            if ($conn->query($sql)) {
                $successCount++;
            } else {
                $errorMessages[] = "Error adding course for program '$program': " . $conn->error;
            }
        }
        
        // Prepare redirect message
        $message = "";
        if ($successCount > 0) {
            $message = "success=" . urlencode("$successCount course(s) added successfully");
        }
        
        if (!empty($errorMessages)) {
            if (!empty($message)) $message .= "&";
            $message .= "error=" . urlencode(implode("; ", $errorMessages));
        }
        
        header("Location: course.php?" . $message);
        exit();
    } else {
        header("Location: course.php?error=" . urlencode("Please select at least one program"));
        exit();
    }
} else {
    header("Location: course.php");
    exit();
}
?>