<?php
include('session_validator.php');
include('includes/db.php');

// Handle form submissions
$alert = "";

// Add new subject
if (isset($_POST['add_subject'])) {
    $subject_name = $conn->real_escape_string(trim($_POST['subject_name']));
    $subject_code = $conn->real_escape_string(trim($_POST['subject_code']));
    $theory_marks = isset($_POST['theory_full_marks']) ? (int)$_POST['theory_full_marks'] : 100;
    $internal_marks = isset($_POST['internal_full_marks']) ? (int)$_POST['internal_full_marks'] : 20;
    $theory_credit = isset($_POST['theory_credit_hour']) ? (float)$_POST['theory_credit_hour'] : 4.0;
    $internal_credit = isset($_POST['internal_credit_hour']) ? (float)$_POST['internal_credit_hour'] : 1.0;
    $type = isset($_POST['type']) ? $conn->real_escape_string($_POST['type']) : 'active';
    
    // Check if subject code already exists
    $check_sql = "SELECT * FROM subjects WHERE subject_code = '$subject_code'";
    $check_result = $conn->query($check_sql);
    
    if ($check_result->num_rows > 0) {
        $alert = "<div class='alert alert-warning alert-dismissible fade show' role='alert'>
                    Subject with code '$subject_code' already exists!
                    <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>&times;</span>
                    </button>
                  </div>";
    } else {
        $sql = "INSERT INTO subjects (subject_name, subject_code, theory_full_marks, internal_full_marks, 
                theory_credit_hour, internal_credit_hour, type) 
                VALUES ('$subject_name', '$subject_code', $theory_marks, $internal_marks, 
                $theory_credit, $internal_credit, '$type')";
        
        if ($conn->query($sql) === TRUE) {
            $alert = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                        Subject '$subject_name' added successfully!
                        <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                      </div>";
        } else {
            $alert = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                        Error: " . $conn->error . "
                        <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                      </div>";
        }
    }
}

// Get current academic year (active one)
$current_academic_year = "";
$academic_year_id = "";
$academic_year_query = "SELECT * FROM academic_years WHERE status = 'active' ORDER BY start_date DESC LIMIT 1";
$academic_year_result = $conn->query($academic_year_query);
if ($academic_year_result->num_rows > 0) {
    $academic_year_row = $academic_year_result->fetch_assoc();
    $current_academic_year = $academic_year_row['ay_ad'];
    $academic_year_id = $academic_year_row['year_id'];
} else {
    $current_academic_year = date('Y') . '-' . (date('Y') + 1);
}

// Assign subjects to class-section
if (isset($_POST['assign_subjects'])) {
    if (isset($_POST['class_id']) && isset($_POST['section_id']) && isset($_POST['subject_ids']) && !empty($_POST['subject_ids'])) {
        $class_id = (int)$_POST['class_id'];
        $section_id = (int)$_POST['section_id'];
        $subject_ids = is_array($_POST['subject_ids']) ? $_POST['subject_ids'] : explode(',', $_POST['subject_ids']);
        
        $academic_year_select = isset($_POST['academic_year']) ? $conn->real_escape_string($_POST['academic_year']) : $current_academic_year;
        $academic_year_id = isset($_POST['academic_year_id']) ? (int)$_POST['academic_year_id'] : 0;
        
        $success_count = 0;
        $error_count = 0;
        $errors = [];
        
        foreach ($subject_ids as $subject_id) {
            $subject_id = (int)$subject_id;
            if ($subject_id <= 0) continue;
            
            $check_sql = "SELECT * FROM class_subject_mapping 
                          WHERE class_id = $class_id 
                          AND section_id = $section_id 
                          AND subject_id = $subject_id";
            
            if ($academic_year_id > 0) {
                $check_sql .= " AND academic_year_id = $academic_year_id";
            } else {
                $check_sql .= " AND academic_year = '$academic_year_select'";
            }
            $check_result = $conn->query($check_sql);
            
            if ($check_result->num_rows == 0) {
                $subject_query = $conn->query("SELECT subject_name FROM subjects WHERE id = $subject_id");
                if ($subject_query->num_rows > 0) {
                    $subject_row = $subject_query->fetch_assoc();
                    $subject_name = $conn->real_escape_string($subject_row['subject_name']);
                    
                    $insert_sql = "INSERT INTO class_subject_mapping 
                                   (class_id, section_id, subject_id, subject_name, academic_year, academic_year_id) 
                                   VALUES ($class_id, $section_id, $subject_id, '$subject_name', '$academic_year_select', $academic_year_id)";
                    
                    if ($conn->query($insert_sql)) {
                        $success_count++;
                    } else {
                        $error_count++;
                        $errors[] = "Error for subject ID $subject_id: " . $conn->error;
                    }
                } else {
                    $error_count++;
                    $errors[] = "Subject ID $subject_id not found";
                }
            } else {
                $success_count++;
            }
        }
        
        $class_name = $conn->query("SELECT class FROM classes WHERE class_id = $class_id")->fetch_assoc()['class'];
        $section_name = $conn->query("SELECT section_name FROM sections WHERE section_id = $section_id")->fetch_assoc()['section_name'];
        
        if ($error_count == 0) {
            $alert = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                        Successfully assigned $success_count subject(s) to $class_name - $section_name for academic year $academic_year_select!
                        <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                      </div>";
        } else {
            $error_msg = "Assigned $success_count subject(s) to $class_name - $section_name, $error_count failed.";
            if (!empty($errors)) {
                $error_msg .= " Errors: " . implode(', ', array_slice($errors, 0, 3));
                if (count($errors) > 3) $error_msg .= "...";
            }
            $alert = "<div class='alert alert-warning alert-dismissible fade show' role='alert'>
                        $error_msg
                        <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                      </div>";
        }
    } else {
        $alert = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                    Please select class, section, and at least one subject!
                    <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>&times;</span>
                    </button>
                  </div>";
    }
}

// Remove subject from class-section
if (isset($_GET['remove_subject'])) {
    $mapping_id = (int)$_GET['remove_subject'];
    
    $delete_sql = "DELETE FROM class_subject_mapping WHERE id = $mapping_id";
    
    if ($conn->query($delete_sql)) {
        $alert = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                    Subject removed from class-section successfully!
                    <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>&times;</span>
                    </button>
                  </div>";
    } else {
        $alert = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                    Error removing subject: " . $conn->error . "
                    <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>&times;</span>
                    </button>
                  </div>";
    }
}

// Remove all subjects from class-section
if (isset($_GET['remove_all'])) {
    $class_id = (int)$_GET['class_id'];
    $section_id = isset($_GET['section_id']) ? (int)$_GET['section_id'] : 0;
    $academic_year = isset($_GET['year']) ? $conn->real_escape_string($_GET['year']) : '';
    $academic_year_id = isset($_GET['year_id']) ? (int)$_GET['year_id'] : 0;
    
    $delete_sql = "DELETE FROM class_subject_mapping WHERE class_id = $class_id";
    if ($section_id > 0) {
        $delete_sql .= " AND section_id = $section_id";
    }
    if ($academic_year_id > 0) {
        $delete_sql .= " AND academic_year_id = $academic_year_id";
    } elseif (!empty($academic_year)) {
        $delete_sql .= " AND academic_year = '$academic_year'";
    }
    
    if ($conn->query($delete_sql)) {
        $class_name = $conn->query("SELECT class FROM classes WHERE class_id = $class_id")->fetch_assoc()['class'];
        $section_text = $section_id > 0 ? "section" : "all sections";
        $alert = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                    All subjects removed from $class_name ($section_text) successfully!
                    <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>&times;</span>
                    </button>
                  </div>";
    } else {
        $alert = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                    Error removing subjects: " . $conn->error . "
                    <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>&times;</span>
                    </button>
                  </div>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Subjects - School Management System</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
    <link rel="stylesheet" href="css/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <script src="js/modernizr/modernizr.min.js"></script>
    <style>
        /* Card Styles */
        .info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .info-card h3 {
            margin: 0 0 10px 0;
            font-size: 1.2em;
            font-weight: 600;
        }
        
        .info-card p {
            margin: 0;
            opacity: 0.9;
        }
        
        /* Step Indicator */
        .step-container {
            display: flex;
            justify-content: space-between;
            margin: 30px 0;
            position: relative;
        }
        
        .step-container::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background: #e0e0e0;
            z-index: 0;
        }
        
        .step {
            flex: 1;
            text-align: center;
            position: relative;
            z-index: 1;
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            background: white;
            border: 3px solid #e0e0e0;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #999;
            margin-bottom: 10px;
        }
        
        .step.active .step-number {
            border-color: #667eea;
            background: #667eea;
            color: white;
        }
        
        .step-label {
            font-size: 0.9em;
            color: #666;
            font-weight: 500;
        }
        
        .step.active .step-label {
            color: #667eea;
            font-weight: 600;
        }
        
        /* Subject Selection */
        .subject-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 2fr));
            gap: 4px;
            max-height: 600px;
            overflow-y: auto;
            padding: 8px;
        }
        
        .subject-card {
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            padding: 5px;
            cursor: pointer;
            transition: all 0.3s;
            background: white;
        }
        
        .subject-card:hover {
            border-color: #667eea;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
            transform: translateY(-2px);
        }
        
        .subject-card.selected {
            border-color: #667eea;
            background: linear-gradient(135deg, #f0f4ff 0%, #e8eeff 100%);
        }
        
        .subject-card-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 8px;
        }
        
        .subject-title {
            font-weight: 600;
            color: #333;
            font-size: 0.95em;
            flex: 1;
        }
        
        .subject-check {
            width: 20px;
            height: 20px;
            border: 2px solid #ddd;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
        }
        
        .subject-card.selected .subject-check {
            background: #667eea;
            border-color: #667eea;
            color: white;
        }
        
        .subject-code {
            font-size: 0.85em;
            color: #666;
            margin-bottom: 4px;
        }
        
        .subject-marks {
            font-size: 0.8em;
            color: #999;
        }
        
        /* Selected Summary */
        .selected-summary {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin: 15px 0;
            min-height: 80px;
        }
        
        .selected-badge {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 6px 12px;
            margin: 4px;
            border-radius: 20px;
            font-size: 0.85em;
        }
        
        .selected-badge .remove-x {
            margin-left: 8px;
            cursor: pointer;
            font-weight: bold;
            opacity: 0.8;
        }
        
        .selected-badge .remove-x:hover {
            opacity: 1;
        }
        
        /* Panel Improvements */
        .panel {
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            margin-bottom: 20px;
            border: none;
        }
        
        .panel-heading {
            background: linear-gradient(to right, #f8f9fa, #ffffff);
            border-bottom: 2px solid #e9ecef;
            padding: 15px 20px;
            border-radius: 8px 8px 0 0;
        }
        
        .panel-title {
            font-weight: 600;
            color: #333;
            font-size: 1.1em;
        }
        
        .panel-body {
            padding: 20px;
        }
        
        /* Form Improvements */
        .form-group label {
            font-weight: 600;
            color: #495057;
            margin-bottom: 8px;
        }
        
        .form-control {
            border-radius: 6px;
            border: 1px solid #ced4da;
            padding: 10px 12px;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        /* Button Improvements */
        .btn {
            border-radius: 6px;
            padding: 10px 20px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
            border: none;
        }
        
        /* Table Improvements */
        .table {
            border-radius: 8px;
            overflow: hidden;
        }
        
        .table thead th {
            background: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
            font-weight: 600;
            color: #495057;
            padding: 12px;
        }
        
        .table tbody tr {
            transition: background 0.2s;
        }
        
        .table tbody tr:hover {
            background: #f8f9fa;
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }
        
        .empty-state i {
            font-size: 3em;
            margin-bottom: 15px;
            opacity: 0.3;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .subject-grid {
                grid-template-columns: 1fr;
            }
            
            .step-container {
                flex-direction: column;
            }
            
            .step-container::before {
                display: none;
            }
            
            .step {
                margin-bottom: 15px;
            }
        }
        
        /* Assignment Table Badge */
        .subject-tag {
            display: inline-block;
            background: #e8eeff;
            color: #667eea;
            padding: 4px 10px;
            margin: 3px;
            border-radius: 4px;
            font-size: 0.85em;
        }
        
        /* Scrollbar */
        .subject-grid::-webkit-scrollbar {
            width: 8px;
        }
        
        .subject-grid::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        .subject-grid::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }
        
        .subject-grid::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
    </style>
</head>
<body class="top-navbar-fixed">
<div class="main-wrapper">
    <?php include('includes/topbar.php'); ?>
    <div class="content-wrapper">
        <div class="content-container">
            <?php include('includes/leftbar.php'); ?>
            
            <div class="main-page">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row page-title-div">
                        <div class="col-md-6">
                            <h2 class="title"><i class="fa fa-book"></i> Manage Subjects</h2>
                        </div>
                        <div class="col-md-6 text-right">
                            <button class="btn btn-primary" data-toggle="modal" data-target="#addSubjectModal">
                                <i class="fa fa-plus-circle"></i> Add New Subject
                            </button>
                        </div>
                    </div>
                    
                    <!-- Breadcrumb -->
                    <div class="row breadcrumb-div">
                        <div class="col-md-12">
                            <ul class="breadcrumb">
                                <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                <li>Subjects</li>
                                <li class="active">Manage Subjects</li>
                            </ul>
                        </div>
                    </div>
                    
                    <!-- Alert Messages -->
                    <?php if($alert): ?>
                        <div class="row">
                            <div class="col-md-12">
                                <?php echo $alert; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Info Card -->
                   <!--  <div class="row">
                        <div class="col-md-12">
                            <div class="info-card">
                                <h3><i class="fa fa-info-circle"></i> Quick Guide</h3>
                                <p>Follow the 3-step process below to assign subjects to your classes. Select a class and section, choose subjects, and assign them for the academic year.</p>
                            </div>
                        </div>
                    </div> -->
                    
                    <!-- Main Assignment Section -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="panel">
                                <div class="panel-heading">
                                    <h5 class="panel-title mb-0">
                                        <i class="fa fa-tasks"></i> Assign Subjects to Class
                                    </h5>
                                </div>
                                <div class="panel-body">
                                    <!-- Step Indicator -->
                               <!--      <div class="step-container">
                                        <div class="step active" id="step1">
                                            <div class="step-number">1</div>
                                            <div class="step-label">Select Class & Section</div>
                                        </div>
                                        <div class="step" id="step2">
                                            <div class="step-number">2</div>
                                            <div class="step-label">Choose Subjects</div>
                                        </div>
                                        <div class="step" id="step3">
                                            <div class="step-number">3</div>
                                            <div class="step-label">Confirm & Assign</div>
                                        </div>
                                    </div> -->
                                    
                                    <form method="POST" action="" id="assignForm">
                                        <!-- Step 1: Class, Section, Year -->
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="class_id"><i class="fa fa-graduation-cap"></i> Select Class *</label>
                                                    <select class="form-control" id="class_id" name="class_id" required>
                                                        <option value="">-- Choose a class --</option>
                                                        <?php
                                                        $classes_query = "SELECT * FROM classes WHERE status = 1 ORDER BY class_numeric";
                                                        $classes_result = $conn->query($classes_query);
                                                        
                                                        while ($class = $classes_result->fetch_assoc()) {
                                                            echo '<option value="' . $class['class_id'] . '">' . 
                                                                 htmlspecialchars($class['class']) . ' (Grade ' . $class['class_numeric'] . ')</option>';
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="section_id"><i class="fa fa-users"></i> Select Section *</label>
                                                    <select class="form-control" id="section_id" name="section_id" required disabled>
                                                        <option value="">-- Select class first --</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="academic_year"><i class="fa fa-calendar"></i> Academic Year *</label>
                                                    <select class="form-control" id="academic_year" name="academic_year" required>
                                                        <option value="">-- Select year --</option>
                                                        <?php
                                                        $academic_years_query = "SELECT * FROM academic_years ORDER BY start_date DESC";
                                                        $academic_years_result = $conn->query($academic_years_query);
                                                        
                                                        if ($academic_years_result->num_rows > 0) {
                                                            while ($year = $academic_years_result->fetch_assoc()) {
                                                                $selected = ($year['year_id'] == $academic_year_id) ? 'selected' : '';
                                                                $display_text = $year['ay_ad'] . ' (' . $year['ay_bs'] . ')';
                                                                if ($year['status'] == 'active') {
                                                                    $display_text .= ' ✓';
                                                                }
                                                                
                                                                echo '<option value="' . $year['ay_ad'] . '" data-year-id="' . $year['year_id'] . '" ' . $selected . '>' . $display_text . '</option>';
                                                            }
                                                        } else {
                                                            echo '<option value="' . $current_academic_year . '" selected>' . $current_academic_year . '</option>';
                                                        }
                                                        ?>
                                                    </select>
                                                    <input type="hidden" name="academic_year_id" id="academic_year_id" value="<?php echo $academic_year_id; ?>">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Step 2: Subject Selection -->
                                        <div class="row" style="margin-top: 20px;">
                                            <div class="col-md-12">
                                                <h5 style="font-weight: 500; color: #495057; margin-bottom: 15px;">
                                                    <i class="fa fa-check-square-o"></i> Select Subjects to Assign
                                                    <span class="badge badge-primary" id="selectedCount">0 selected</span>
                                                </h5>
                                                
                                                <div class="subject-grid">
                                                    <?php
                                                    $available_query = "SELECT * FROM subjects WHERE status = 1 ORDER BY subject_name";
                                                    $available_result = $conn->query($available_query);

                                                    if ($available_result->num_rows > 0) {
                                                        while ($subject = $available_result->fetch_assoc()) {
                                                            $marks = [];
                                                            if ($subject['theory_full_marks'] > 0) {
                                                                $marks[] = "Theory: {$subject['theory_full_marks']}";
                                                            }
                                                            if ($subject['internal_full_marks'] > 0) {
                                                                $marks[] = "Internal: {$subject['internal_full_marks']}";
                                                            }
                                                            $marksText = implode(" | ", $marks);

                                                            echo '
                                                            <div class="subject-card" 
                                                                data-id="' . $subject['id'] . '"
                                                                data-name="' . htmlspecialchars($subject['subject_name']) . '"
                                                                data-code="' . htmlspecialchars($subject['subject_code']) . '">
                                                                <div class="subject-card-header">
                                                                    <div class="subject-title">' . htmlspecialchars($subject['subject_name']) . '</div>
                                                                    <div class="subject-check">
                                                                        <i class="fa fa-check"></i>
                                                                    </div>
                                                                </div>
                                                                <div class="subject-code">Code: ' . htmlspecialchars($subject['subject_code']) . '</div>
                                                                <div class="subject-marks">' . $marksText . '</div>
                                                            </div>';
                                                        }
                                                    } else {
                                                        echo '<div class="empty-state">
                                                                <i class="fa fa-inbox"></i>
                                                                <p>No active subjects available</p>
                                                              </div>';
                                                    }
                                                    ?>
                                                </div>
                                                <input type="hidden" name="subject_ids" id="selectedSubjectsInput">
                                            </div>
                                        </div>

                                        <!-- Selected Subjects Summary -->
                                        <div class="row" style="margin-top: 20px;">
                                            <div class="col-md-12">
                                                <h5 style="font-weight: 400; color: #495057; margin-bottom: 10px;">
                                                    <i class="fa fa-list-alt"></i> Selected Subjects
                                                </h5>
                                                <div class="selected-summary" id="selectedSummary">
                                                    <div class="empty-state" style="padding: 20px;">
                                                        <i class="fa fa-hand-pointer-o"></i>
                                                        <p>Click on subjects above to select them</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Step 3: Action Buttons -->
                                        <div class="row" style="margin-top: 20px;">
                                            <div class="col-md-12 text-right">
                                                <button type="button" id="clearSelection" class="btn btn-secondary">
                                                    <i class="fa fa-eraser"></i> Clear Selection
                                                </button>
                                                <button type="submit" name="assign_subjects" class="btn btn-success btn-lg">
                                                    <i class="fa fa-check-circle"></i> Assign Selected Subjects
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Current Assignments Section -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="panel">
                                <div class="panel-heading">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h5 class="panel-title mb-0">
                                                <i class="fa fa-list"></i> Current Subject Assignments
                                            </h5>
                                        </div>
                                        <div class="col-md-6 text-right">
                                            <select class="form-control" id="filter_year" style="width: 250px; display: inline-block;">
                                                <option value="all">All Academic Years</option>
                                                <?php
                                                $filter_years_query = "SELECT DISTINCT academic_year FROM class_subject_mapping WHERE academic_year IS NOT NULL ORDER BY academic_year DESC";
                                                $filter_years_result = $conn->query($filter_years_query);
                                                
                                                while ($year = $filter_years_result->fetch_assoc()) {
                                                    $selected = ($year['academic_year'] == $current_academic_year) ? 'selected' : '';
                                                    echo '<option value="' . htmlspecialchars($year['academic_year']) . '" ' . $selected . '>' . htmlspecialchars($year['academic_year']) . '</option>';
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="panel-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="assignmentsTable">
                                            <thead>
                                                <tr>
                                                    <th width="5%">#</th>
                                                    <th width="15%">Class</th>
                                                    <th width="15%">Section</th>
                                                    <th width="40%">Subjects</th>
                                                    <th width="15%">Academic Year</th>
                                                    <th width="10%">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $assignments_query = "
                                                    SELECT c.class_id, c.class, c.class_numeric,
                                                           s.section_id, s.section_name,
                                                           csm.academic_year,
                                                           GROUP_CONCAT(DISTINCT csm.subject_name ORDER BY csm.subject_name SEPARATOR '|||') as subjects,
                                                           COUNT(DISTINCT csm.subject_id) as subject_count
                                                    FROM classes c
                                                    JOIN class_section cs ON c.class_id = cs.class_id AND cs.status = 1
                                                    JOIN sections s ON cs.section_id = s.section_id AND s.status = 1
                                                    LEFT JOIN class_subject_mapping csm ON c.class_id = csm.class_id 
                                                        AND cs.section_id = csm.section_id
                                                    WHERE c.status = 1
                                                    GROUP BY c.class_id, cs.section_id, csm.academic_year
                                                    ORDER BY c.class_numeric, s.section_name, csm.academic_year DESC
                                                ";
                                                $assignments_result = $conn->query($assignments_query);
                                                
                                                if ($assignments_result->num_rows > 0) {
                                                    $counter = 1;
                                                    while ($row = $assignments_result->fetch_assoc()) {
                                                        $academic_year = $row['academic_year'] ?: 'Not specified';
                                                        echo '<tr data-year="' . htmlspecialchars($academic_year) . '">';
                                                        echo '<td>' . $counter . '</td>';
                                                        echo '<td><strong>' . htmlspecialchars($row['class']) . '</strong><br><small class="text-muted">Grade ' . $row['class_numeric'] . '</small></td>';
                                                        echo '<td>' . htmlspecialchars($row['section_name']) . '</td>';
                                                        echo '<td>';
                                                        if ($row['subjects']) {
                                                            $subjects = explode('|||', $row['subjects']);
                                                            foreach ($subjects as $subject) {
                                                                echo '<span class="subject-tag">' . htmlspecialchars($subject) . '</span>';
                                                            }
                                                            echo '<div><small class="text-muted">' . $row['subject_count'] . ' subject(s) assigned</small></div>';
                                                        } else {
                                                            echo '<span class="text-muted"><i>No subjects assigned</i></span>';
                                                        }
                                                        echo '</td>';
                                                        echo '<td><span class="badge badge-info">' . htmlspecialchars($academic_year) . '</span></td>';
                                                        echo '<td>';
                                                        if ($row['subjects']) {
                                                            echo '<a href="?remove_all=' . $row['class_id'] . '&section_id=' . $row['section_id'] . '&year=' . urlencode($academic_year) . '" class="btn btn-sm btn-danger" 
                                                                   onclick="return confirm(\'Are you sure you want to remove all subjects from ' . htmlspecialchars($row['class']) . ' - ' . htmlspecialchars($row['section_name']) . ' for ' . htmlspecialchars($academic_year) . '?\')">
                                                                    <i class="fa fa-trash"></i>
                                                                  </a>';
                                                        }
                                                        echo '</td>';
                                                        echo '</tr>';
                                                        $counter++;
                                                    }
                                                } else {
                                                    echo '<tr><td colspan="6">
                                                            <div class="empty-state">
                                                                <i class="fa fa-info-circle"></i>
                                                                <p>No subject assignments found. Start by assigning subjects above.</p>
                                                            </div>
                                                          </td></tr>';
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- All Subjects Reference -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="panel">
                                <div class="panel-heading">
                                    <h5 class="panel-title mb-0">
                                        <i class="fa fa-book"></i> All Subjects Library
                                        <span class="badge badge-primary"><?php 
                                            $total = $conn->query("SELECT COUNT(*) as count FROM subjects")->fetch_assoc()['count'];
                                            echo $total;
                                        ?></span>
                                    </h5>
                                </div>
                                <div class="panel-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead>
                                                <tr>
                                                    <th width="5%">#</th>
                                                    <th width="25%">Subject Name</th>
                                                    <th width="15%">Subject Code</th>
                                                    <th width="15%">Theory Marks</th>
                                                    <th width="15%">Internal Marks</th>
                                                    <th width="15%">Credits (T/I)</th>
                                                    <th width="10%">Type</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $subjects_query = "SELECT * FROM subjects ORDER BY subject_name";
                                                $subjects_result = $conn->query($subjects_query);
                                                
                                                if ($subjects_result->num_rows > 0) {
                                                    $counter = 1;
                                                    while ($subject = $subjects_result->fetch_assoc()) {
                                                        echo '<tr>';
                                                        echo '<td>' . $counter . '</td>';
                                                        echo '<td><strong>' . htmlspecialchars($subject['subject_name']) . '</strong></td>';
                                                        echo '<td><code>' . htmlspecialchars($subject['subject_code']) . '</code></td>';
                                                        echo '<td>' . $subject['theory_full_marks'] . '</td>';
                                                        echo '<td>' . $subject['internal_full_marks'] . '</td>';
                                                        echo '<td>' . $subject['theory_credit_hour'] . ' / ' . $subject['internal_credit_hour'] . '</td>';
                                                        echo '<td>';
                                                        if ($subject['type'] == 'active') {
                                                            echo '<span class="badge badge-success">Active</span>';
                                                        } else {
                                                            echo '<span class="badge badge-secondary">Non-Credit</span>';
                                                        }
                                                        echo '</td>';
                                                        echo '</tr>';
                                                        $counter++;
                                                    }
                                                } else {
                                                    echo '<tr><td colspan="7">
                                                            <div class="empty-state">
                                                                <i class="fa fa-inbox"></i>
                                                                <p>No subjects found. Click "Add New Subject" to create one.</p>
                                                            </div>
                                                          </td></tr>';
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Subject Modal -->
<div class="modal fade" id="addSubjectModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                <h5 class="modal-title">
                    <i class="fa fa-plus-circle"></i> Add New Subject
                </h5>
                <button type="button" class="close" data-dismiss="modal" style="color: white;">
                    <span>&times;</span>
                </button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="subject_name"><i class="fa fa-book"></i> Subject Name *</label>
                                <input type="text" class="form-control" id="subject_name" name="subject_name" placeholder="e.g., Mathematics" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="subject_code"><i class="fa fa-code"></i> Subject Code *</label>
                                <input type="text" class="form-control" id="subject_code" name="subject_code" placeholder="e.g., MATH101" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="theory_full_marks"><i class="fa fa-file-text"></i> Theory Marks</label>
                                <input type="number" class="form-control" id="theory_full_marks" name="theory_full_marks" value="100" min="0">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="internal_full_marks"><i class="fa fa-pencil"></i> Internal Marks</label>
                                <input type="number" class="form-control" id="internal_full_marks" name="internal_full_marks" value="20" min="0">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="theory_credit_hour"><i class="fa fa-star"></i> Theory Credit Hours</label>
                                <input type="number" class="form-control" id="theory_credit_hour" name="theory_credit_hour" value="4.0" min="0" step="0.01">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="internal_credit_hour"><i class="fa fa-star-half-o"></i> Internal Credit Hours</label>
                                <input type="number" class="form-control" id="internal_credit_hour" name="internal_credit_hour" value="1.0" min="0" step="0.01">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="type"><i class="fa fa-tag"></i> Subject Type</label>
                        <select class="form-control" id="type" name="type">
                            <option value="active">Active (Credit)</option>
                            <option value="Non-Credit">Non-Credit</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fa fa-times"></i> Cancel
                    </button>
                    <button type="submit" name="add_subject" class="btn btn-primary">
                        <i class="fa fa-save"></i> Add Subject
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="js/jquery/jquery-2.2.4.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<script src="js/pace/pace.min.js"></script>
<script src="js/lobipanel/lobipanel.min.js"></script>
<script src="js/iscroll/iscroll.js"></script>
<script src="js/prism/prism.js"></script>
<script src="js/select2/select2.min.js"></script>
<script src="js/main.js"></script>

<script>
$(document).ready(function() {
    let selectedSubjects = [];
    
    // Initialize select2 if available
    if ($.fn.select2) {
        $('#class_id, #section_id, #academic_year, #filter_year').select2({
            theme: 'bootstrap',
            width: '100%'
        });
    }
    
    // Update step indicators
    function updateSteps() {
        const classSelected = $('#class_id').val() !== '';
        const sectionSelected = $('#section_id').val() !== '';
        const subjectsSelected = selectedSubjects.length > 0;
        
        // Step 1
        if (classSelected && sectionSelected) {
            $('#step1').addClass('active');
            $('#step2').addClass('active');
        } else {
            $('#step2').removeClass('active');
            $('#step3').removeClass('active');
        }
        
        // Step 3
        if (subjectsSelected) {
            $('#step3').addClass('active');
        } else {
            $('#step3').removeClass('active');
        }
    }
    
    // Update academic_year_id when academic year select changes
    $('#academic_year').change(function() {
        var selectedOption = $(this).find('option:selected');
        var yearId = selectedOption.data('year-id') || 0;
        $('#academic_year_id').val(yearId);
        updateSteps();
    });
    
    // Class selection change
    $('#class_id').change(function() {
        const classId = $(this).val();
        updateSteps();
        loadSections(classId);
    });
    
    // Section selection change
    $('#section_id').change(function() {
        updateSteps();
    });
    
    // Select subject card
    $(document).on('click', '.subject-card', function() {
        const subjectId = $(this).data('id');
        const subjectName = $(this).data('name');
        const subjectCode = $(this).data('code');
        
        // Check if already selected
        const index = selectedSubjects.findIndex(s => s.id == subjectId);
        
        if (index === -1) {
            // Add to selection
            selectedSubjects.push({
                id: subjectId,
                name: subjectName,
                code: subjectCode
            });
            $(this).addClass('selected');
        } else {
            // Remove from selection
            selectedSubjects.splice(index, 1);
            $(this).removeClass('selected');
        }
        
        updateSelectedDisplay();
        updateSteps();
    });
    
    // Clear selection
    $('#clearSelection').click(function() {
        selectedSubjects = [];
        $('.subject-card').removeClass('selected');
        updateSelectedDisplay();
        updateSteps();
    });
    
    // Update selected subjects display
    function updateSelectedDisplay() {
        const container = $('#selectedSummary');
        const countBadge = $('#selectedCount');
        const input = $('#selectedSubjectsInput');
        
        countBadge.text(selectedSubjects.length + ' selected');
        
        if (selectedSubjects.length === 0) {
            container.html(`
                <div class="empty-state" style="padding: 20px;">
                    <i class="fa fa-hand-pointer-o"></i>
                    <p>Click on subjects above to select them</p>
                </div>
            `);
            input.val('');
            return;
        }
        
        let html = '';
        selectedSubjects.forEach(function(subject) {
            html += `
                <span class="selected-badge">
                    ${subject.name} (${subject.code})
                    <span class="remove-x" onclick="removeSelectedSubject(${subject.id})">×</span>
                </span>
            `;
        });
        
        container.html(html);
        
        // Update hidden input
        const subjectIds = selectedSubjects.map(s => s.id);
        input.val(subjectIds.join(','));
    }
    
    // Form validation
    $('#assignForm').submit(function(e) {
        const classId = $('#class_id').val();
        const sectionId = $('#section_id').val();
        const academicYear = $('#academic_year').val();
        
        if (!classId) {
            alert('Please select a class!');
            e.preventDefault();
            return false;
        }
        
        if (!sectionId) {
            alert('Please select a section!');
            e.preventDefault();
            return false;
        }
        
        if (!academicYear) {
            alert('Please select an academic year!');
            e.preventDefault();
            return false;
        }
        
        if (selectedSubjects.length === 0) {
            alert('Please select at least one subject!');
            e.preventDefault();
            return false;
        }
        
        const className = $('#class_id option:selected').text().split(' (')[0];
        const sectionName = $('#section_id option:selected').text();
        const academicYearText = $('#academic_year option:selected').text().split(' ✓')[0];
        
        return confirm(`Assign ${selectedSubjects.length} subject(s) to ${className} - ${sectionName} for academic year ${academicYearText}?`);
    });
    
    // Filter assignments by year
    $('#filter_year').change(function() {
        const year = $(this).val();
        const rows = $('#assignmentsTable tbody tr');
        
        if (year === 'all') {
            rows.show();
        } else {
            rows.each(function() {
                if ($(this).data('year') == year) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }
    });
    
    // Auto-dismiss alerts after 5 seconds
    setTimeout(function() {
        $('.alert').fadeOut('slow', function() {
            $(this).alert('close');
        });
    }, 5000);
});

// Function to remove selected subject
function removeSelectedSubject(subjectId) {
    const index = selectedSubjects.findIndex(s => s.id == subjectId);
    if (index !== -1) {
        selectedSubjects.splice(index, 1);
        $(`.subject-card[data-id="${subjectId}"]`).removeClass('selected');
        
        const container = $('#selectedSummary');
        const countBadge = $('#selectedCount');
        
        countBadge.text(selectedSubjects.length + ' selected');
        
        if (selectedSubjects.length === 0) {
            container.html(`
                <div class="empty-state" style="padding: 20px;">
                    <i class="fa fa-hand-pointer-o"></i>
                    <p>Click on subjects above to select them</p>
                </div>
            `);
            $('#selectedSubjectsInput').val('');
            $('#step3').removeClass('active');
        } else {
            let html = '';
            selectedSubjects.forEach(function(subject) {
                html += `
                    <span class="selected-badge">
                        ${subject.name} (${subject.code})
                        <span class="remove-x" onclick="removeSelectedSubject(${subject.id})">×</span>
                    </span>
                `;
            });
            container.html(html);
            $('#selectedSubjectsInput').val(selectedSubjects.map(s => s.id).join(','));
        }
    }
}

// Function to load sections based on selected class
function loadSections(classId) {
    if (!classId) {
        $('#section_id').html('<option value="">-- Select class first --</option>').prop('disabled', true);
        if ($.fn.select2) {
            $('#section_id').trigger('change.select2');
        }
        return;
    }
    
    $.ajax({
        url: 'ajax/get_sections.php',
        type: 'GET',
        data: { class_id: classId },
        success: function(response) {
            try {
                const sections = JSON.parse(response);
                let options = '<option value="">-- Select section --</option>';
                
                if (sections.length > 0) {
                    sections.forEach(function(section) {
                        options += `<option value="${section.section_id}">${section.section_name}</option>`;
                    });
                    $('#section_id').html(options).prop('disabled', false);
                } else {
                    $('#section_id').html('<option value="">No sections available</option>').prop('disabled', true);
                }
                
                if ($.fn.select2) {
                    $('#section_id').trigger('change.select2');
                }
            } catch(e) {
                console.error('Error parsing sections:', e);
                $('#section_id').html('<option value="">Error loading sections</option>').prop('disabled', true);
            }
        },
        error: function() {
            $('#section_id').html('<option value="">Error loading sections</option>').prop('disabled', true);
        }
    });
}
</script>
</body>
</html>