<?php include("../database/auth_check.php"); ?>

<?php
$con = mysqli_connect("localhost","root","","WSAS");
if(!$con){
    die("Connection failed");
}

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

    $course_id = $_POST['course_id'];
    $subject_id = $_POST['subject_id'];
    $semester   = $_POST['semester'];
    $year_level = $_POST['year_level'];

    // Check if already assigned
    $check = mysqli_query($con, "SELECT * FROM course_subject 
                                 WHERE course_id='$course_id' 
                                 AND subject_id='$subject_id'");
    if(mysqli_num_rows($check) > 0){
    echo "<script>
        window.onload = function() {
            showMessage('⚠️ This subject is already assigned to this course.');
        }
    </script>";
}

    // Insert new assignment
    $sql = "INSERT INTO course_subject (course_id, subject_id, semester, year_level) 
            VALUES ('$course_id', '$subject_id', '$semester', '$year_level')";
    if(mysqli_query($con, $sql)){
        echo "<script>
            window.onload = function() {
                document.getElementById('successModal').style.display = 'block';
            }
        </script>";
    
    } else {
    echo "<script>
        window.onload = function() {
            showMessage('⚠️ This subject is already assigned to this course.');
        }
    </script>";
}
}

// Fetch subjects and courses for datalist
$subject_result = mysqli_query($con, "SELECT * FROM adminsubject");
$course_result  = mysqli_query($con, "SELECT * FROM admincourse");

// Fetch all assigned subjects for display
$assigned_result = mysqli_query($con, "
    SELECT cs.*, s.subject_code, s.subject_name, c.course_code, c.course_name, c.major 
    FROM course_subject cs
    LEFT JOIN adminsubject s ON cs.subject_id = s.subject_id
    LEFT JOIN admincourse c ON cs.course_id = c.course_id
    ORDER BY cs.year_level, cs.semester
");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assign Subjects - Admin</title>
    <link rel="shortcut icon" type="x-icon" href="../images/logo.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
<link rel="stylesheet" href="../Style/navstyle.css">

<style>
/* Dashboard Layout */
.dashboard-container {
    display: flex;
    min-height: 100vh;
    font-family: "Segoe UI", sans-serif;
    background: #f4f6f8;
}

.mainbar {
    margin-left: 260px;
    width: calc(100% - 260px);
    flex: 1;
    display: flex;
    flex-direction: column;
}
.open-btn {
    background-color: #4a9c3f;
    color: #fff;
    padding: 10px 18px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    text-decoration: none;
    transition: 0.3s;
}
.open-btn:hover { background-color: #3e8c36; }

form {
    margin-top: 20px;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 10px;
}

form label {
    display: block;
    margin-bottom: 5px;
    font-weight: 600;
    color: #555;
}

form input[list], form input[type="text"] {
    width: 100%;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 6px;
}

form button {
    width: 100%;
    padding: 12px;
    background: #4a9c3f;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 15px;
    cursor: pointer;
}
form button:hover { background: #43a047; }

/* Radio buttons */
.required { color: red; margin-left: 3px; }
.radio-group {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    margin-bottom: 15px;
}
.radio-group label {
    display: flex;
    align-items: center;
    gap: 5px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
}
.radio-group input[type="radio"] { accent-color: #4a9c3f; width:16px;height:16px;cursor:pointer; }

/* Table styling */
table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
    background: #fff;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
table th, table td { padding: 12px; border: 1px solid #ccc; text-align: center; }
table th { background: #2b5820; color: #fff; font-weight: 600; }
table tr:nth-child(even) { background: #f8f8f8; }
table tr:hover { background: rgba(74,156,63,0.1); transition: 0.3s; }

/* Responsive */
@media (max-width:1024px){ .mainbar { margin-left:0; margin-top:70px; } }

/* MODAL BACKGROUND (THIS IS WHAT YOU'RE MISSING) */
.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  z-index: 1000;
  align-items: center;
  justify-content: center;
}

/* animation (optional but nice) */
@keyframes pop {
  from { transform: scale(0.8); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}
/* ASSIGN MODAL */
#assignConfirmModal .modal-content {
  background: #fff;
  width: 350px;
  max-width: 90%;
  margin: 15% auto;
  padding: 20px;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 8px 25px rgba(0,0,0,0.2);
  animation: pop 0.25s ease;
}

#assignConfirmModal h3 {
  font-size: 16px;
  margin-bottom: 20px;
  color: #333;
}

#assignConfirmModal .btn-group {
  display: flex;
  justify-content: center;
  gap: 15px;
}

#confirmAssignBtn {
  background: #4a9c3f;
  color: #fff;
  border: none;
  padding: 8px 18px;
  border-radius: 6px;
  cursor: pointer;
}

#confirmAssignBtn:hover {
  background: #3e8c36;
}

#cancelAssignBtn {
  background: #ccc;
  color: #333;
  border: none;
  padding: 8px 18px;
  border-radius: 6px;
  cursor: pointer;
}

#cancelAssignBtn:hover {
  background: #aaa;
}

#successModal .modal-content {
  background: #fff;
  width: 350px;
  max-width: 90%;
  margin: 15% auto;
  padding: 20px;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 8px 25px rgba(0,0,0,0.2);
  animation: pop 0.25s ease;
}

#okSuccessBtn {
  background: #4a9c3f;
  color: #fff;
  border: none;
  padding: 8px 18px;
  border-radius: 6px;
  cursor: pointer;
}

#okSuccessBtn:hover {
  background: #3e8c36;
}

/* ===== MESSAGE MODAL CONTENT ===== */
#messageModal .modal-content {
  background: #fff;
  width: 350px;
  max-width: 90%;
  margin: 15% auto;
  padding: 20px;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 8px 25px rgba(0,0,0,0.2);
  animation: pop 0.25s ease;
}

/* message text */
#messageText {
  font-size: 15px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 500;
}

/* button group (reuse existing layout) */
#messageModal .btn-group {
  display: flex;
  justify-content: center;
  gap: 12px;
}

/* OK button */
#okMessageBtn {
  background: #4a9c3f;
  color: #fff;
  border: none;
  padding: 8px 18px;
  border-radius: 6px;
  cursor: pointer;
  transition: 0.2s;
}

#okMessageBtn:hover {
  background: #3e8c36;
}
</style>
</head>
<body>
<div class="dashboard-container">
<?php include('adminnav.php'); ?>

<aside class="mainbar">
    <form method="POST">
        <input type="hidden" name="assign" value="1">
        <label>Subject: <span class="required">*</span></label>
        <input list="subjectList" name="subject_id_input" placeholder="Type or select subject..." required>
        <datalist id="subjectList">
            <?php while($row = mysqli_fetch_assoc($subject_result)){
                $display = $row['subject_code']." - ".$row['subject_name'];
                echo "<option value='{$display}' data-id='{$row['subject_id']}'></option>";
            } ?>
        </datalist>

        <label>Course: <span class="required">*</span></label>
        <input list="courseList" name="course_id_input" placeholder="Type or select course..." required>
        <datalist id="courseList">
            <?php while($row = mysqli_fetch_assoc($course_result)){
                $display = $row['course_code']." - ".$row['course_name'];
                if(!empty($row['major'])) $display .= " ({$row['major']})";
                echo "<option value='{$display}' data-id='{$row['course_id']}'></option>";
            } ?>
        </datalist>

        <label>Semester: <span class="required">*</span></label>
        <div class="radio-group">
            <label><input type="radio" name="semester" value="1st" required> 1st Semester</label>
            <label><input type="radio" name="semester" value="2nd" required> 2nd Semester</label>
        </div>

        <label>Year Level: <span class="required">*</span></label>
        <div class="radio-group">
            <label><input type="radio" name="year_level" value="1st" required> 1st Year</label>
            <label><input type="radio" name="year_level" value="2nd" required> 2nd Year</label>
            <label><input type="radio" name="year_level" value="3rd" required> 3rd Year</label>
            <label><input type="radio" name="year_level" value="4th" required> 4th Year</label>
        </div>

        <button type="submit" name="assign">Assign Subject</button>
    </form>

<!-- ASSIGN CONFIRM MODAL -->

</aside>
</div>

<div id="assignConfirmModal" class="modal">
  <div class="modal-content">
    <h3>Are you sure you want to assign this subject?</h3>

    <div class="btn-group">
      <button id="confirmAssignBtn">Yes</button>
      <button id="cancelAssignBtn">Cancel</button>
    </div>
  </div>
</div>

<div id="successModal" class="modal">
  <div class="modal-content">
    <h3>✅ Subject assigned to course successfully!</h3>

    <div class="btn-group">
      <button id="okSuccessBtn">OK</button>
    </div>
  </div>
</div>

<div id="messageModal" class="modal">
  <div class="modal-content">
    <h3 id="messageText"></h3>

    <div class="btn-group">
      <button id="okMessageBtn">OK</button>
    </div>
  </div>
</div>

<script>
const form = document.querySelector('form');
const subjectInput = document.querySelector('input[name="subject_id_input"]');
const subjectOptions = document.querySelectorAll('#subjectList option');

const courseInput = document.querySelector('input[name="course_id_input"]');
const courseOptions = document.querySelectorAll('#courseList option');

// Modal elements
const modal = document.getElementById("assignConfirmModal");
const confirmBtn = document.getElementById("confirmAssignBtn");
const cancelBtn = document.getElementById("cancelAssignBtn");

let isReadyToSubmit = false;

form.addEventListener('submit', function(e){
    if (!isReadyToSubmit) {
        e.preventDefault();

        const subjectMatch = Array.from(subjectOptions).find(opt => opt.value === subjectInput.value);
        const courseMatch = Array.from(courseOptions).find(opt => opt.value === courseInput.value);

        if(subjectMatch && courseMatch){

            // Store IDs temporarily
            form.dataset.subjectId = subjectMatch.getAttribute('data-id');
            form.dataset.courseId = courseMatch.getAttribute('data-id');

            // Show modal
            modal.style.display = "block";

        } else {
            alert('Please select valid Subject and Course from the list.');
        }
    }
});

// Cancel
cancelBtn.addEventListener("click", () => {
    modal.style.display = "none";
});

// Confirm submit
confirmBtn.addEventListener("click", () => {

    // Create hidden inputs
    let subHidden = document.createElement('input');
    subHidden.type = 'hidden';
    subHidden.name = 'subject_id';
    subHidden.value = form.dataset.subjectId;
    form.appendChild(subHidden);

    let courseHidden = document.createElement('input');
    courseHidden.type = 'hidden';
    courseHidden.name = 'course_id';
    courseHidden.value = form.dataset.courseId;
    form.appendChild(courseHidden);

    isReadyToSubmit = true;
    modal.style.display = "none";

    // Trigger real submit (IMPORTANT)
    form.querySelector('button[name="assign"]').click();
});

// Close when clicking outside
window.addEventListener("click", (e) => {
    if (e.target === modal) {
        modal.style.display = "none";
    }
});

const successModal = document.getElementById("successModal");
const okSuccessBtn = document.getElementById("okSuccessBtn");

okSuccessBtn.addEventListener("click", () => {
    window.location.href = "assignsub.php";
});

// close when clicking outside
window.addEventListener("click", (e) => {
    if (e.target === successModal) {
        successModal.style.display = "none";
    }
});

const messageModal = document.getElementById("messageModal");
const messageText = document.getElementById("messageText");
const okMessageBtn = document.getElementById("okMessageBtn");

function showMessage(msg){
    messageText.innerText = msg;
    messageModal.style.display = "block";
}

okMessageBtn.addEventListener("click", () => {
    messageModal.style.display = "none";
});

window.addEventListener("click", (e) => {
    if (e.target === messageModal) {
        messageModal.style.display = "none";
    }
});
</script>

</body>
</html>