<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in and is admin or teacher
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Get data for dropdowns
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();

// Handle clearing default layout
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['clear_default_layout'])) {
    unset($_SESSION['default_subject_layout']);
    $success_message = 'ডিফল্ট লেআউট সফলভাবে মুছে ফেলা হয়েছে।';
}

// Handle saving subject layout
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_subject_layout'])) {
    $layout_name = trim($_POST['layout_name']);
    $subject_order = $_POST['subject_order'] ?? '';
    $set_as_default = isset($_POST['set_as_default']);
    
    if (!empty($layout_name) && !empty($subject_order)) {
        // Save layout to session
        $_SESSION['subject_layout_' . $layout_name] = $subject_order;
        
        // Set as default if requested
        if ($set_as_default) {
            $_SESSION['default_subject_layout'] = $layout_name;
            $success_message = "লেআউট '$layout_name' সফলভাবে সংরক্ষিত এবং ডিফল্ট হিসেবে সেট করা হয়েছে!";
        } else {
            $success_message = "লেআউট '$layout_name' সফলভাবে সংরক্ষিত হয়েছে!";
        }
    } else {
        // More descriptive error message
        if (empty($layout_name) && empty($subject_order)) {
            $error_message = 'লেআউটের নাম এবং বিষয় ক্রম প্রদান করুন!';
        } else if (empty($layout_name)) {
            $error_message = 'লেআউটের নাম প্রদান করুন!';
        } else {
            $error_message = 'অন্ততপক্ষে একটি বিষয় ড্রপ করুন!';
        }
    }
}

// Function to apply custom subject layout
function applySubjectLayout($distributions, $layout_name = null) {
    // If no layout specified, check for default layout
    if ($layout_name === null && isset($_SESSION['default_subject_layout'])) {
        $layout_name = $_SESSION['default_subject_layout'];
    }
    
    // If we have a layout name, apply it
    if ($layout_name !== null && isset($_SESSION['subject_layout_' . $layout_name])) {
        $saved_order = explode(',', $_SESSION['subject_layout_' . $layout_name]);
        
        // Group distributions by subject_id
        $subject_groups = [];
        foreach ($distributions as $dist) {
            $subject_groups[$dist['subject_id']][] = $dist;
        }
        
        $ordered_distributions = [];
        
        // First add subjects in the saved order
        foreach ($saved_order as $subject_id) {
            if (isset($subject_groups[$subject_id])) {
                foreach ($subject_groups[$subject_id] as $dist) {
                    $ordered_distributions[] = $dist;
                }
            }
        }
        
        // Then add any remaining subjects not in the saved order
        foreach ($subject_groups as $subject_id => $dists) {
            $found = in_array($subject_id, $saved_order);
            if (!$found) {
                foreach ($dists as $dist) {
                    $ordered_distributions[] = $dist;
                }
            }
        }
        
        return $ordered_distributions;
    }
    
    // Return original distributions if no layout to apply
    return $distributions;
}

// Get saved layouts from session
$saved_layouts = [];
foreach ($_SESSION as $key => $value) {
    if (strpos($key, 'subject_layout_') === 0) {
        $layout_name = substr($key, 14); // Remove 'subject_layout_' prefix
        $saved_layouts[] = $layout_name;
    }
}

// Get default layout if set
$default_layout = isset($_SESSION['default_subject_layout']) ? $_SESSION['default_subject_layout'] : '';
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>বিষয় সাজানো - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .cursor-move {
            cursor: move;
        }
        
        .draggable-item {
            transition: all 0.2s ease;
            user-select: none;
            position: relative;
        }
        
        .draggable-item:hover {
            background-color: #e9ecef !important;
            transform: translateY(-2px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .draggable-item.dragging {
            opacity: 0.5;
            background-color: #007bff !important;
            color: white;
        }
        
        .draggable-item::after {
            content: "ডাবল ক্লিক করুন";
            position: absolute;
            right: 5px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 0.7em;
            color: #6c757d;
            opacity: 0;
            transition: opacity 0.2s;
        }
        
        .draggable-item:hover::after {
            opacity: 0.7;
        }
        
        .droppable-area {
            transition: all 0.2s ease;
        }
        
        .droppable-area.drag-over {
            background-color: #d1ecf1 !important;
            border-color: #007bff !important;
            box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
        }
        
        .border-dashed {
            border-style: dashed !important;
        }
        
        #subject-order .draggable-item::after {
            content: "ডাবল ক্লিক করে সরান";
        }
    </style>
</head>
<body class="bengali-text">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="setup.php">
                    <i class="fas fa-cog"></i> মার্কস সেটআপ
                </a>
                <a class="nav-link" href="quick_setup.php">
                    <i class="fas fa-bolt"></i> দ্রুত সেটআপ
                </a>
                <a class="nav-link" href="entry.php">
                    <i class="fas fa-edit"></i> মার্কস এন্ট্রি
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h4 class="mb-0"><i class="fas fa-sort"></i> বিষয় সাজানো (Subject Arrangement)</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i> <strong>নোট:</strong> এই লেআউট নিচের মার্কশীট ভিউতে প্রয়োগ হবে:
                            <ul class="mb-0 mt-1">
                                <li>marksheet.php</li>
                                <li>all_subjects_marksheet.php</li>
                                <li>combined_bangla_english_marksheet.php</li>
                                <li>bulk_marksheet_printer.php</li>
                            </ul>
                        </div>
                        
                        <div class="alert alert-warning">
                            <i class="fas fa-mouse"></i> <strong>ডাবল ক্লিক নির্দেশনা:</strong>
                            <ul class="mb-0 mt-1">
                                <li>বিষয় তালিকা থেকে ডাবল ক্লিক করে কাঙ্ক্ষিত ক্রমে সরান</li>
                                <li>কাঙ্ক্ষিত ক্রম থেকে ডাবল ক্লিক করে বিষয় তালিকায় ফেরত আনুন</li>
                            </ul>
                        </div>
                        
                        <!-- Saved Layouts -->
                        <?php if (!empty($saved_layouts)): ?>
                        <div class="mb-4">
                            <h5><i class="fas fa-folder"></i> সংরক্ষিত লেআউটসমূহ</h5>
                            <div class="d-flex flex-wrap gap-2">
                                <?php foreach ($saved_layouts as $layout): ?>
                                    <a href="#" class="btn btn-sm <?php echo ($default_layout == $layout) ? 'btn-success' : 'btn-outline-primary'; ?>">
                                        <?php echo htmlspecialchars($layout); ?>
                                        <?php if ($default_layout == $layout): ?>
                                            <span class="badge bg-light text-dark">ডিফল্ট</span>
                                        <?php endif; ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Clear Default Layout -->
                        <?php if ($default_layout): ?>
                        <div class="mb-3">
                            <form method="POST" action="" class="d-inline">
                                <button type="submit" name="clear_default_layout" class="btn btn-sm btn-outline-danger">
                                    <i class="fas fa-times"></i> ডিফল্ট লেআউট মুছুন (<?php echo htmlspecialchars($default_layout); ?>)
                                </button>
                            </form>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Draggable Container -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="border rounded p-3 bg-light">
                                    <h5 class="text-center">বিষয়সমূহ</h5>
                                    <p class="text-muted text-center mb-3">ডাবল ক্লিক করে কাঙ্ক্ষিত ক্রমে সরান</p>
                                    <div id="available-subjects" class="draggable-area" style="min-height: 400px; max-height: 500px; overflow-y: auto;">
                                        <?php foreach ($subjects as $subject): ?>
                                            <div class="draggable-item p-2 mb-2 bg-white border rounded cursor-move" 
                                                 data-subject-id="<?php echo $subject['id']; ?>">
                                                <?php echo htmlspecialchars($subject['name']); ?> (<?php echo htmlspecialchars($subject['code']); ?>)
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="border rounded p-3 bg-white">
                                    <h5 class="text-center">কাঙ্ক্ষিত ক্রম</h5>
                                    <p class="text-muted text-center mb-3">ডাবল ক্লিক করে বিষয় তালিকায় ফেরত আনুন</p>
                                    <div id="subject-order" class="droppable-area border border-dashed rounded p-2" style="min-height: 400px; max-height: 500px; overflow-y: auto;">
                                        <div class="text-center text-muted py-5" id="drop-placeholder">
                                            <i class="fas fa-arrow-down"></i><br>
                                            বিষয়গুলো এখানে ড্রপ করুন অথবা ডাবল ক্লিক করুন
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Save Layout Form -->
                        <div class="card bg-light">
                            <div class="card-body">
                                <h5><i class="fas fa-save"></i> লেআউট সংরক্ষণ করুন</h5>
                                <form method="POST" action="" name="save_subject_layout">
                                    <div class="row">
                                        <div class="col-md-5">
                                            <input type="text" name="layout_name" class="form-control" placeholder="লেআউটের নাম দিন" required>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check mt-2">
                                                <input class="form-check-input" type="checkbox" name="set_as_default" id="setAsDefault">
                                                <label class="form-check-label" for="setAsDefault">
                                                    ডিফল্ট হিসেবে সেট করুন
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <button type="submit" name="save_subject_layout" class="btn btn-primary w-100">
                                                <i class="fas fa-save"></i> সংরক্ষণ করুন
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            // Make items draggable
            $('.draggable-item').attr('draggable', true);
            
            $('.draggable-item').on('dragstart', function(e) {
                e.originalEvent.dataTransfer.setData('text/plain', $(this).data('subject-id'));
                $(this).addClass('dragging');
            });
            
            $('.draggable-item').on('dragend', function() {
                $(this).removeClass('dragging');
            });
            
            // Make drop zone droppable
            $('#subject-order').on('dragover', function(e) {
                e.preventDefault();
                $(this).addClass('drag-over');
            });
            
            $('#subject-order').on('dragleave', function() {
                $(this).removeClass('drag-over');
            });
            
            $('#subject-order').on('drop', function(e) {
                e.preventDefault();
                $(this).removeClass('drag-over');
                
                const subjectId = e.originalEvent.dataTransfer.getData('text/plain');
                const draggedElement = $(`.draggable-item[data-subject-id='${subjectId}'].dragging`);
                
                if (draggedElement.length) {
                    // Clone the element to allow multiple drops
                    const clonedElement = draggedElement.clone();
                    clonedElement.removeClass('dragging');
                    
                    // Remove existing element with same subject ID if exists
                    $(`#subject-order [data-subject-id='${subjectId}']`).remove();
                    
                    // Add to drop zone
                    $('#drop-placeholder').hide();
                    $(this).append(clonedElement);
                    
                    // Add remove functionality
                    clonedElement.on('dblclick', function() {
                        $(this).remove();
                        if ($('#subject-order [data-subject-id]').length === 0) {
                            $('#drop-placeholder').show();
                        }
                    });
                }
            });
            
            // Double-click functionality for moving items to ordered list
            $('#available-subjects .draggable-item').on('dblclick', function() {
                const subjectId = $(this).data('subject-id');
                const subjectText = $(this).text();
                
                // Check if item already exists in ordered list
                if ($(`#subject-order [data-subject-id='${subjectId}']`).length === 0) {
                    // Create new element for ordered list
                    const newElement = $(`<div class="draggable-item p-2 mb-2 bg-white border rounded cursor-move" data-subject-id="${subjectId}">${subjectText}</div>`);
                    
                    // Add to drop zone
                    $('#drop-placeholder').hide();
                    $('#subject-order').append(newElement);
                    
                    // Add remove functionality (double-click to remove)
                    newElement.on('dblclick', function() {
                        $(this).remove();
                        if ($('#subject-order [data-subject-id]').length === 0) {
                            $('#drop-placeholder').show();
                        }
                    });
                }
            });
            
            // Double-click functionality for removing items from ordered list (back to available)
            $('#subject-order').on('dblclick', '.draggable-item', function() {
                $(this).remove();
                if ($('#subject-order [data-subject-id]').length === 0) {
                    $('#drop-placeholder').show();
                }
            });
            
            // Add hidden input to form for subject order
            $('form[name="save_subject_layout"]').on('submit', function(e) {
                const orderedSubjects = [];
                $('#subject-order [data-subject-id]').each(function() {
                    orderedSubjects.push($(this).data('subject-id'));
                });
                
                // Create hidden input
                let hiddenInput = $('input[name="subject_order"]');
                if (hiddenInput.length === 0) {
                    hiddenInput = $('<input type="hidden" name="subject_order">');
                    $(this).append(hiddenInput); // Append to form
                }
                
                hiddenInput.val(orderedSubjects.join(','));
                
                if (orderedSubjects.length === 0) {
                    e.preventDefault();
                    alert('অন্ততপক্ষে একটি বিষয় ড্রপ করুন!');
                    return false;
                }
            });
        });
    </script>
</body>
</html>