<?php
/**
 * Subject Combinations Management
 * Allows admins to create, edit, and manage subject combinations
 */

session_start();
require_once 'config.php';

// Role checking
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== ROLE_ADMIN) {
    header("location: login.php");
    exit;
}

$school_id = $_SESSION["school_id"];
$message = "";
$error = "";

// Handle AJAX requests
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    
    switch ($_GET['action']) {
        case 'get_combinations':
            $combinations = getCombinations($conn, $school_id);
            echo json_encode(['success' => true, 'data' => $combinations]);
            exit;
            
        case 'get_subjects':
            $subjects = getSubjects($conn, $school_id);
            echo json_encode(['success' => true, 'data' => $subjects]);
            exit;
            
        case 'validate_combination':
            $combination = $_GET['combination'] ?? '';
            $validation = validateCombination($combination, $conn, $school_id);
            echo json_encode($validation);
            exit;
    }
}

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'add_combination':
            $result = addCombination($conn, $school_id, $_POST);
            if ($result['success']) {
                $message = "Combination created successfully!";
            } else {
                $error = $result['message'];
            }
            break;
            
        case 'edit_combination':
            $result = editCombination($conn, $school_id, $_POST);
            if ($result['success']) {
                $message = "Combination updated successfully!";
            } else {
                $error = $result['message'];
            }
            break;
            
        case 'delete_combination':
            $result = deleteCombination($conn, $school_id, $_POST['combination_id']);
            if ($result['success']) {
                $message = "Combination deleted successfully!";
            } else {
                $error = $result['message'];
            }
            break;
    }
}

// Functions
function getSubjects($conn, $school_id) {
    $sql = "SELECT subject_id, subject_name, subject_code, subject_category FROM subjects WHERE school_id = ? ORDER BY subject_code";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $subjects = [];
    while ($row = $result->fetch_assoc()) {
        $subjects[] = $row;
    }
    $stmt->close();
    return $subjects;
}

function getCombinations($conn, $school_id) {
    // Check if subject_combination_templates table exists
    $sql = "SHOW TABLES LIKE 'subject_combination_templates'";
    $result = $conn->query($sql);
    
    if ($result->num_rows == 0) {
        // Table doesn't exist, create it
        createCombinationTable($conn);
    }
    
    $sql = "SELECT combination_id, combination_code, combination_name, subject_codes, subject_names, is_active FROM subject_combination_templates WHERE school_id = ? ORDER BY combination_code";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $combinations = [];
    while ($row = $result->fetch_assoc()) {
        $combinations[] = $row;
    }
    $stmt->close();
    
    // If no combinations exist, create default ones
    if (empty($combinations)) {
        createDefaultCombinations($conn, $school_id);
        return getCombinations($conn, $school_id);
    }
    
    return $combinations;
}

function createCombinationTable($conn) {
    $sql = "CREATE TABLE subject_combination_templates (
        combination_id INT AUTO_INCREMENT PRIMARY KEY,
        school_id INT NOT NULL,
        combination_code VARCHAR(20) NOT NULL,
        combination_name VARCHAR(255) NOT NULL,
        subject_codes VARCHAR(50) NOT NULL,
        subject_names VARCHAR(500) NOT NULL,
        is_active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_school_combination (school_id, combination_code)
    )";
    $conn->query($sql);
}

function createDefaultCombinations($conn, $school_id) {
    $default_combinations = [
        ['PCM', 'Physics, Chemistry, Mathematics'],
        ['PEM', 'Physics, English, Mathematics'],
        ['HEG', 'History, Economics, Geography'],
        ['BCG', 'Biology, Chemistry, Geography'],
        ['PCG', 'Physics, Chemistry, Geography'],
        ['MEG', 'Mathematics, Economics, Geography'],
        ['ACG', 'Agriculture, Chemistry, Geography'],
        ['AEG', 'Art, Economics, Geography'],
        ['PEQ', 'Physics, Economics, English']
    ];
    
    foreach ($default_combinations as $combo) {
        $code = $combo[0];
        $name = $combo[1];
        
        // Get subject names for validation
        $subjects = getSubjectsByCodes($conn, $school_id, $code);
        if (!empty($subjects)) {
            $subject_names = implode(', ', array_column($subjects, 'subject_name'));
            
            $sql = "INSERT INTO subject_combination_templates (school_id, combination_code, combination_name, subject_codes, subject_names, is_active) VALUES (?, ?, ?, ?, ?, 1)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("issss", $school_id, $code, $name, $code, $subject_names);
            $stmt->execute();
            $stmt->close();
        }
    }
}

function getSubjectsByCodes($conn, $school_id, $codes) {
    $codes_array = str_split(strtoupper(preg_replace('/[^A-Z]/', '', $codes)));
    if (empty($codes_array)) return [];
    
    $placeholders = str_repeat('?,', count($codes_array) - 1) . '?';
    $sql = "SELECT subject_id, subject_name, subject_code FROM subjects WHERE school_id = ? AND subject_code IN ($placeholders) ORDER BY subject_code";
    
    $stmt = $conn->prepare($sql);
    $params = array_merge([$school_id], $codes_array);
    $stmt->bind_param(str_repeat('i', count($codes_array) + 1), ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    $subjects = [];
    while ($row = $result->fetch_assoc()) {
        $subjects[] = $row;
    }
    $stmt->close();
    return $subjects;
}

function validateCombination($combination, $conn, $school_id) {
    if (empty($combination)) {
        return ['success' => false, 'message' => 'Combination code is required'];
    }
    
    $codes = str_split(strtoupper(preg_replace('/[^A-Z]/', '', $combination)));
    if (empty($codes)) {
        return ['success' => false, 'message' => 'No valid subject codes found'];
    }
    
    $subjects = getSubjectsByCodes($conn, $school_id, $combination);
    if (empty($subjects)) {
        return ['success' => false, 'message' => 'No valid subjects found for this combination'];
    }
    
    $subject_names = implode(', ', array_column($subjects, 'subject_name'));
    return [
        'success' => true,
        'subjects' => $subjects,
        'subject_names' => $subject_names,
        'code' => strtoupper($combination)
    ];
}

function addCombination($conn, $school_id, $data) {
    $code = trim($data['combination_code'] ?? '');
    $name = trim($data['combination_name'] ?? '');
    $subjects_input = trim($data['subjects_input'] ?? '');
    
    if (empty($code) || empty($name) || empty($subjects_input)) {
        return ['success' => false, 'message' => 'All fields are required'];
    }
    
    // Validate combination
    $validation = validateCombination($subjects_input, $conn, $school_id);
    if (!$validation['success']) {
        return $validation;
    }
    
    // Check if combination code already exists
    $sql = "SELECT combination_id FROM subject_combination_templates WHERE school_id = ? AND combination_code = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("is", $school_id, $code);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $stmt->close();
        return ['success' => false, 'message' => 'Combination code already exists'];
    }
    $stmt->close();
    
    // Insert new combination
    $subject_names = $validation['subject_names'];
    $sql = "INSERT INTO subject_combination_templates (school_id, combination_code, combination_name, subject_codes, subject_names, is_active) VALUES (?, ?, ?, ?, ?, 1)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("issss", $school_id, $code, $name, strtoupper($subjects_input), $subject_names);
    
    if ($stmt->execute()) {
        $stmt->close();
        return ['success' => true, 'message' => 'Combination added successfully'];
    } else {
        $stmt->close();
        return ['success' => false, 'message' => 'Failed to add combination'];
    }
}

function editCombination($conn, $school_id, $data) {
    $id = $data['combination_id'] ?? '';
    $name = trim($data['edit_combination_name'] ?? '');
    $subjects_input = trim($data['edit_subjects_input'] ?? '');
    
    if (empty($id) || empty($name) || empty($subjects_input)) {
        return ['success' => false, 'message' => 'All fields are required'];
    }
    
    // Validate combination
    $validation = validateCombination($subjects_input, $conn, $school_id);
    if (!$validation['success']) {
        return $validation;
    }
    
    // Update combination
    $subject_names = $validation['subject_names'];
    $sql = "UPDATE subject_combination_templates SET combination_name = ?, subject_codes = ?, subject_names = ? WHERE combination_id = ? AND school_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssiii", $name, strtoupper($subjects_input), $subject_names, $id, $school_id);
    
    if ($stmt->execute()) {
        $stmt->close();
        return ['success' => true, 'message' => 'Combination updated successfully'];
    } else {
        $stmt->close();
        return ['success' => false, 'message' => 'Failed to update combination'];
    }
}

function deleteCombination($conn, $school_id, $combination_id) {
    if (empty($combination_id)) {
        return ['success' => false, 'message' => 'Combination ID is required'];
    }
    
    $sql = "DELETE FROM subject_combination_templates WHERE combination_id = ? AND school_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $combination_id, $school_id);
    
    if ($stmt->execute()) {
        $stmt->close();
        return ['success' => true, 'message' => 'Combination deleted successfully'];
    } else {
        $stmt->close();
        return ['success' => false, 'message' => 'Failed to delete combination'];
    }
}

$combinations = getCombinations($conn, $school_id);
$subjects = getSubjects($conn, $school_id);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subject Combinations Management</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #eee;
        }
        .btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        .btn:hover {
            background: #0056b3;
        }
        .btn-success {
            background: #28a745;
        }
        .btn-success:hover {
            background: #1e7e34;
        }
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background: #e0a800;
        }
        .btn-danger {
            background: #dc3545;
        }
        .btn-danger:hover {
            background: #c82333;
        }
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .alert-danger {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover {
            color: black;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table th, table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        table th {
            background: #f8f9fa;
            font-weight: bold;
        }
        .subject-item {
            background: #e3f2fd;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            margin: 2px;
            display: inline-block;
        }
        .checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        .checkbox-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .checkbox-item input[type="checkbox"] {
            width: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-layer-group"></i> Subject Combinations Management</h1>
            <a href="admin_students.php" class="btn"><i class="fas fa-arrow-left"></i> Back to Students</a>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <div style="margin-bottom: 20px;">
            <button class="btn btn-success" onclick="openAddModal()">
                <i class="fas fa-plus"></i> Add New Combination
            </button>
        </div>

        <table>
            <thead>
                <tr>
                    <th>Code</th>
                    <th>Name</th>
                    <th>Subjects</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="combinationsTableBody">
                <?php foreach ($combinations as $combo): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($combo['combination_code']); ?></strong></td>
                    <td><?php echo htmlspecialchars($combo['combination_name']); ?></td>
                    <td>
                        <?php 
                        $subjects = explode(', ', $combo['subject_names']);
                        foreach ($subjects as $subject) {
                            echo '<span class="subject-item">' . htmlspecialchars($subject) . '</span>';
                        }
                        ?>
                    </td>
                    <td>
                        <?php if ($combo['is_active']): ?>
                            <span style="color: green;"><i class="fas fa-check"></i> Active</span>
                        <?php else: ?>
                            <span style="color: red;"><i class="fas fa-times"></i> Inactive</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <button class="btn btn-warning" onclick="openEditModal(<?php echo $combo['combination_id']; ?>)">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <button class="btn btn-danger" onclick="deleteCombination(<?php echo $combo['combination_id']; ?>)">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Add Combination Modal -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('addModal')">&times;</span>
            <h2>Add New Combination</h2>
            <form id="addForm" onsubmit="submitAddForm(event)">
                <div class="form-group">
                    <label for="combination_code">Combination Code:</label>
                    <input type="text" id="combination_code" name="combination_code" placeholder="e.g., PCM" maxlength="10" required>
                    <small>Enter the abbreviation for this combination</small>
                </div>
                
                <div class="form-group">
                    <label for="combination_name">Combination Name:</label>
                    <input type="text" id="combination_name" name="combination_name" placeholder="e.g., Physics, Chemistry, Mathematics" required>
                    <small>Full name describing the combination</small>
                </div>
                
                <div class="form-group">
                    <label>Select Subjects:</label>
                    <div class="checkbox-group" id="subjectsCheckboxes">
                        <?php foreach ($subjects as $subject): ?>
                        <div class="checkbox-item">
                            <input type="checkbox" id="subject_<?php echo $subject['subject_id']; ?>" 
                                   value="<?php echo $subject['subject_code']; ?>" 
                                   onchange="updateSubjectsInput()">
                            <label for="subject_<?php echo $subject['subject_id']; ?>">
                                <?php echo htmlspecialchars($subject['subject_code'] . ' - ' . $subject['subject_name']); ?>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="subjects_input">Subject Codes:</label>
                    <input type="text" id="subjects_input" name="subjects_input" placeholder="Select subjects above or type manually" readonly>
                    <small>Auto-generated from selected subjects</small>
                </div>
                
                <button type="submit" class="btn btn-success">Add Combination</button>
            </form>
        </div>
    </div>

    <!-- Edit Combination Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('editModal')">&times;</span>
            <h2>Edit Combination</h2>
            <form id="editForm" onsubmit="submitEditForm(event)">
                <input type="hidden" id="edit_combination_id" name="combination_id">
                
                <div class="form-group">
                    <label for="edit_combination_code">Combination Code:</label>
                    <input type="text" id="edit_combination_code" name="edit_combination_code" readonly>
                    <small>Code cannot be changed</small>
                </div>
                
                <div class="form-group">
                    <label for="edit_combination_name">Combination Name:</label>
                    <input type="text" id="edit_combination_name" name="edit_combination_name" required>
                </div>
                
                <div class="form-group">
                    <label>Select Subjects:</label>
                    <div class="checkbox-group" id="editSubjectsCheckboxes">
                        <?php foreach ($subjects as $subject): ?>
                        <div class="checkbox-item">
                            <input type="checkbox" id="edit_subject_<?php echo $subject['subject_id']; ?>" 
                                   value="<?php echo $subject['subject_code']; ?>" 
                                   onchange="updateEditSubjectsInput()">
                            <label for="edit_subject_<?php echo $subject['subject_id']; ?>">
                                <?php echo htmlspecialchars($subject['subject_code'] . ' - ' . $subject['subject_name']); ?>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="edit_subjects_input">Subject Codes:</label>
                    <input type="text" id="edit_subjects_input" name="edit_subjects_input" readonly>
                </div>
                
                <button type="submit" class="btn btn-success">Update Combination</button>
            </form>
        </div>
    </div>

    <script>
        function openAddModal() {
            document.getElementById('addModal').style.display = 'block';
        }
        
        function openEditModal(id) {
            // Load combination data via AJAX
            fetch(`?action=get_combinations`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const combo = data.data.find(c => c.combination_id == id);
                        if (combo) {
                            document.getElementById('edit_combination_id').value = combo.combination_id;
                            document.getElementById('edit_combination_code').value = combo.combination_code;
                            document.getElementById('edit_combination_name').value = combo.combination_name;
                            document.getElementById('edit_subjects_input').value = combo.subject_codes;
                            
                            // Check the appropriate checkboxes
                            const codes = combo.subject_codes.split('');
                            codes.forEach(code => {
                                const checkbox = document.querySelector(`input[value="${code}"]`);
                                if (checkbox) checkbox.checked = true;
                            });
                            
                            document.getElementById('editModal').style.display = 'block';
                        }
                    }
                });
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function updateSubjectsInput() {
            const checkboxes = document.querySelectorAll('#subjectsCheckboxes input[type="checkbox"]:checked');
            const codes = Array.from(checkboxes).map(cb => cb.value);
            document.getElementById('subjects_input').value = codes.join('');
        }
        
        function updateEditSubjectsInput() {
            const checkboxes = document.querySelectorAll('#editSubjectsCheckboxes input[type="checkbox"]:checked');
            const codes = Array.from(checkboxes).map(cb => cb.value);
            document.getElementById('edit_subjects_input').value = codes.join('');
        }
        
        function submitAddForm(event) {
            event.preventDefault();
            const formData = new FormData(event.target);
            formData.append('action', 'add_combination');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
            });
        }
        
        function submitEditForm(event) {
            event.preventDefault();
            const formData = new FormData(event.target);
            formData.append('action', 'edit_combination');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
            });
        }
        
        function deleteCombination(id) {
            if (confirm('Are you sure you want to delete this combination?')) {
                const formData = new FormData();
                formData.append('action', 'delete_combination');
                formData.append('combination_id', id);
                
                fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error: ' + error.message);
                });
            }
        }
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                if (event.target == modal) {
                    modal.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>