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

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$site_address = $settings['site_address'] ?? 'ঠিকানা: গ্রাম/থানা, জেলা, বাংলাদেশ';
$logo_image = $settings['logo_image'] ?? null;
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

// Get teacher's assigned classes if user is a teacher
$teacher_id = null;
$assigned_class_ids = [];
if ($_SESSION['user_role'] == 'teacher') {
    // Get teacher ID
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
        
        // Get assigned class IDs
        $stmt = $pdo->prepare("SELECT DISTINCT c.id FROM classes c WHERE (c.class_teacher_id = ? OR c.id IN (SELECT class_id FROM class_subjects WHERE teacher_id = ?)) AND c.status = 'active'");
        $stmt->execute([$teacher_id, $teacher_id]);
        $assigned_classes = $stmt->fetchAll();
        $assigned_class_ids = array_column($assigned_classes, 'id');
    }
}

// Get search parameters
$class_id = $_GET['class_id'] ?? $_POST['class_id'] ?? '';
$session = $_GET['session'] ?? $_POST['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? $_POST['exam_type'] ?? '';
$student_search = $_GET['student_search'] ?? $_POST['student_search'] ?? '';
$student_id = $_GET['student_id'] ?? $_POST['student_id'] ?? '';

// Handle clearing default layout
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['clear_default_layout'])) {
    unset($_SESSION['default_layout']);
    
    // Redirect to prevent resubmission
    header("Location: custom_draggable_marksheet.php?student_id=$student_id&session=$session&exam_type=$exam_type");
    exit();
}

// Handle layout saving
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_layout'])) {
    $layout_name = $_POST['layout_name'];
    $subject_order = $_POST['subject_order'];
    $set_as_default = isset($_POST['set_as_default']) ? true : false;
    
    // Save layout to database or session
    $_SESSION['custom_layout_' . $layout_name] = $subject_order;
    
    // Set as default if requested
    if ($set_as_default) {
        $_SESSION['default_layout'] = $layout_name;
    }
    
    // Redirect to prevent resubmission
    header("Location: custom_draggable_marksheet.php?student_id=$student_id&session=$session&exam_type=$exam_type&saved=1&layout=" . urlencode($layout_name));
    exit();
}

$student = null;
$results = [];
$subjects = [];
$merit_position = null;
$students_in_class = [];
$gpa = 0.00; // Add GPA variable

// Get classes for dropdown
if ($_SESSION['user_role'] == 'teacher' && !empty($assigned_class_ids)) {
    // Teacher: only show assigned classes
    $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
    $stmt = $pdo->prepare("SELECT id, name, section FROM classes WHERE id IN ($placeholders) AND status = 'active' ORDER BY name, section");
    $stmt->execute($assigned_class_ids);
    $classes = $stmt->fetchAll();
} else {
    // Admin: show all classes
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
    $classes = $stmt->fetchAll();
}

// Get sessions for dropdown
$stmt = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC");
$sessions = $stmt->fetchAll();

// Get exam types for dropdown
$stmt = $pdo->query("SELECT DISTINCT exam_type FROM results ORDER BY exam_type");
$exam_types = $stmt->fetchAll();

// Check if we're showing student list (after first search)
$show_student_list = false;
if ($class_id && $session && $exam_type) {
    $show_student_list = true;
    
    // Get students based on class, session, and exam type
    $stmt = $pdo->prepare("
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
        FROM students s 
        WHERE s.class_id = ? AND s.status = 'active'
        AND EXISTS (
            SELECT 1 FROM results r 
            WHERE r.student_id = s.id 
            AND r.session = ? 
            AND r.exam_type = ?
        )
        ORDER BY s.roll_number, s.first_name, s.last_name
    ");
    $stmt->execute([$class_id, $session, $exam_type]);
    $all_students_in_class = $stmt->fetchAll();
    
    // Filter students based on search term
    if (!empty($student_search)) {
        $students_in_class = array_filter($all_students_in_class, function($student) use ($student_search) {
            $search_term = strtolower($student_search);
            return strpos(strtolower($student['first_name']), $search_term) !== false ||
                   strpos(strtolower($student['last_name']), $search_term) !== false ||
                   strpos($student['roll_number'], $search_term) !== false ||
                   strpos($student['student_id'], $search_term) !== false;
        });
    } else {
        $students_in_class = $all_students_in_class;
    }
}

if ($student_id && $session && $exam_type) {
    // Fetch student details
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section 
        FROM students s 
        JOIN classes c ON s.class_id = c.id 
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if (!$student) {
        die("Student not found");
    }
    
    // Fetch results for this student
    $stmt = $pdo->prepare("
        SELECT r.*, s.name as subject_name, s.code as subject_code, s.id as subject_id
        FROM results r
        JOIN subjects s ON r.subject_id = s.id
        WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
        ORDER BY s.name
    ");
    $stmt->execute([$student_id, $session, $exam_type]);
    $raw_results = $stmt->fetchAll();
    
    // Process results to combine subjects if needed
    $results = [];
    $bangla_subjects = [];
    $english_subjects = [];
    
    foreach ($raw_results as $result) {
        // Ensure subject_id is set (use subject_id from subjects table)
        if (!isset($result['subject_id'])) {
            $result['subject_id'] = $result['id']; // Fallback to result id if subject_id not set
        }
        
        // Ensure required fields are set
        if (!isset($result['full_marks']) || $result['full_marks'] <= 0) {
            $result['full_marks'] = 100; // Default value
        }
        
        if (!isset($result['grade_point'])) {
            // Calculate grade point if not set
            $grade_info = calculateGrade($result['marks_obtained'], $result['full_marks']);
            $result['grade'] = $grade_info['grade'];
            $result['grade_point'] = $grade_info['point'];
        }
        
        // Check if this is a Bangla subject (code starts with 'BAN')
        if (strpos($result['subject_code'], 'BAN') === 0) {
            $bangla_subjects[] = $result;
        }
        // Check if this is an English subject (code starts with 'ENG')
        elseif (strpos($result['subject_code'], 'ENG') === 0) {
            $english_subjects[] = $result;
        }
        else {
            // Regular subject, add as is
            $results[] = $result;
        }
    }
    
    // Combine Bangla subjects if there are any
    if (!empty($bangla_subjects)) {
        $combined_bangla = combineBanglaSubjects($bangla_subjects);
        if ($combined_bangla) {
            $results[] = $combined_bangla;
        }
    }
    
    // Combine English subjects if there are any
    if (!empty($english_subjects)) {
        $combined_english = combineEnglishSubjects($english_subjects);
        if ($combined_english) {
            $results[] = $combined_english;
        }
    }
    
    // Sort results by subject name
    usort($results, function($a, $b) {
        return strcmp($a['subject_name'], $b['subject_name']);
    });
    
    // Apply custom layout if saved
    $layout_to_use = null;
    
    // Check for specific layout request
    if (isset($_GET['layout']) && isset($_SESSION['custom_layout_' . $_GET['layout']])) {
        $layout_to_use = $_GET['layout'];
    }
    // Otherwise use default layout if set
    elseif (isset($_SESSION['default_layout']) && isset($_SESSION['custom_layout_' . $_SESSION['default_layout']])) {
        $layout_to_use = $_SESSION['default_layout'];
    }
    
    // Apply the layout if we have one
    if ($layout_to_use !== null) {
        $saved_order = explode(',', $_SESSION['custom_layout_' . $layout_to_use]);
        $ordered_results = [];
        
        // First add subjects in the saved order
        foreach ($saved_order as $subject_id) {
            foreach ($results as $result) {
                if ($result['subject_id'] == $subject_id) {
                    $ordered_results[] = $result;
                    break;
                }
            }
        }
        
        // Then add any remaining subjects not in the saved order
        foreach ($results as $result) {
            $found = false;
            foreach ($saved_order as $subject_id) {
                if ($result['subject_id'] == $subject_id) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $ordered_results[] = $result;
            }
        }
        
        $results = $ordered_results;
    }
    
    // Calculate total marks and GPA
    $total_obtained = 0;
    $total_marks = 0;
    $total_grade_points = 0;
    $passed_subjects = 0;
    $total_subjects = 0;
    
    foreach ($results as $result) {
        // Skip combined subjects for counting (they're counted as one)
        if ($result['subject_id'] == 'combined_bangla' || $result['subject_id'] == 'combined_english') {
            $total_subjects++;
            $total_obtained += $result['marks_obtained'];
            $total_marks += $result['full_marks'];
            
            // For combined subjects, we calculate grade point differently
            $total_grade_points += (isset($result['grade_point']) ? $result['grade_point'] : 0);
            
            // Ensure full_marks is set
            if (!isset($result['full_marks'])) {
                $result['full_marks'] = 100;
            }
            
            if ($result['grade'] != 'F') {
                $passed_subjects++;
            }
        } else {
            $total_subjects++;
            $total_obtained += $result['marks_obtained'];
            $total_marks += (isset($result['full_marks']) ? $result['full_marks'] : 100);
            $total_grade_points += (isset($result['grade_point']) ? $result['grade_point'] : 0);
            
            if ($result['grade'] != 'F') {
                $passed_subjects++;
            }
        }
    }
    
    // Calculate GPA
    if ($total_subjects > 0) {
        $gpa = $total_grade_points / $total_subjects;
    }

    // Calculate percentage
    $percentage = ($total_marks > 0) ? ($total_obtained / $total_marks) * 100 : 0;
    
    // Get merit position
    $stmt = $pdo->prepare("
        SELECT COUNT(*) + 1 as merit_position 
        FROM (
            SELECT s.id, 
                   SUM(r.marks_obtained) as total_marks
            FROM students s
            JOIN results r ON s.id = r.student_id
            WHERE s.class_id = ? AND r.session = ? AND r.exam_type = ?
            GROUP BY s.id
            HAVING total_marks > ?
        ) as higher_ranked
    ");
    $stmt->execute([$student['class_id'], $session, $exam_type, $total_obtained]);
    $merit_result = $stmt->fetch();
    $merit_position = $merit_result['merit_position'];
}

// Function to combine Bangla subjects
function combineBanglaSubjects($bangla_results) {
    if (empty($bangla_results)) return null;
    
    // If only one Bangla subject, return it as is but mark it as combined
    if (count($bangla_results) == 1) {
        $result = $bangla_results[0];
        $result['subject_name'] = 'বাংলা(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        $result['mcq_marks_array'] = [$result['mcq_marks']]; // Convert to array for display
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_bangla';
        
        // Ensure grade_point is set
        if (!isset($result['grade_point'])) {
            $grade_info = calculateGrade($result['marks_obtained'], $result['full_marks']);
            $result['grade'] = $grade_info['grade'];
            $result['grade_point'] = $grade_info['point'];
        }
        
        return $result;
    }
    
    // For multiple Bangla subjects, combine them
    $combined = [
        'subject_name' => 'বাংলা(একত্রে)',
        'subject_code' => 'CBAN',
        'subject_id' => 'combined_bangla',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for display
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Consider only first 2 Bangla papers for CQ/MCQ averaging
    $considered_results = array_slice($bangla_results, 0, 2);

    // Sum up other marks from all Bangla subjects; don't include CQ/MCQ here
    foreach ($bangla_results as $result) {
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    
    // Average CQ and MCQ based on first 2 papers
    $cq_total = 0;
    $mcq_total = 0;
    foreach ($considered_results as $result) {
        $cq_total += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $mcq_total += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual MCQ marks
    }
    
    $count = count($considered_results);
    if ($count > 0) {
        $combined['cq_marks'] = $cq_total / $count;
        $combined['mcq_marks'] = $mcq_total / $count;
    }
    
    // Calculate obtained marks as sum of averaged CQ and MCQ
    $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
    
    // Average full and pass marks over total Bangla results
    $total_count = count($bangla_results);
    if ($total_count > 0) {
        $combined['full_marks'] = $combined['full_marks'] / $total_count;
        $combined['pass_marks'] = $combined['pass_marks'] / $total_count;
    }
    
    // Calculate grade for combined subject
    $grade_info = calculateGrade($combined['marks_obtained'], $combined['full_marks']);
    $combined['grade'] = $grade_info['grade'];
    $combined['grade_point'] = $grade_info['point'];
    
    return $combined;
}

// Function to combine English subjects
function combineEnglishSubjects($english_results) {
    if (empty($english_results)) return null;
    
    // If only one English subject, return it as is but mark it as combined
    if (count($english_results) == 1) {
        $result = $english_results[0];
        $result['subject_name'] = 'ইংরেজি(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        $result['mcq_marks_array'] = [$result['mcq_marks']]; // Convert to array for display
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_english';
        
        // Ensure grade_point is set
        if (!isset($result['grade_point'])) {
            $grade_info = calculateGrade($result['marks_obtained'], $result['full_marks']);
            $result['grade'] = $grade_info['grade'];
            $result['grade_point'] = $grade_info['point'];
        }
        
        return $result;
    }
    
    // For multiple English subjects, combine them
    $combined = [
        'subject_name' => 'ইংরেজি(একত্রে)',
        'subject_code' => 'CENG',
        'subject_id' => 'combined_english',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for display
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Sum up the marks from all English subjects
    foreach ($english_results as $result) {
        $combined['cq_marks'] += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $combined['mcq_marks'] += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual MCQ marks
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['marks_obtained'] += $result['marks_obtained'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    
    // Average full and pass marks
    $total_count = count($english_results);
    if ($total_count > 0) {
        $combined['full_marks'] = $combined['full_marks'] / $total_count;
        $combined['pass_marks'] = $combined['pass_marks'] / $total_count;
    }
    
    // Calculate grade for combined subject
    $grade_info = calculateGrade($combined['marks_obtained'], $combined['full_marks']);
    $combined['grade'] = $grade_info['grade'];
    $combined['grade_point'] = $grade_info['point'];
    
    return $combined;
}

// Function to calculate grade from marks
function calculateGrade($marks_obtained, $full_marks) {
    if ($full_marks <= 0) return ['grade' => 'F', 'point' => 0.00];
    
    $percentage = ($marks_obtained / $full_marks) * 100;
    
    if ($percentage >= 80) return ['grade' => 'A+', 'point' => 5.00];
    if ($percentage >= 70) return ['grade' => 'A', 'point' => 4.00];
    if ($percentage >= 60) return ['grade' => 'A-', 'point' => 3.50];
    if ($percentage >= 50) return ['grade' => 'B', 'point' => 3.00];
    if ($percentage >= 40) return ['grade' => 'C', 'point' => 2.00];
    if ($percentage >= 33) return ['grade' => 'D', 'point' => 1.00];
    return ['grade' => 'F', 'point' => 0.00];
}

// Function to calculate grade from GPA
function calculateGradeFromGPA($gpa) {
    if ($gpa >= 5.00) return 'A+';
    if ($gpa >= 4.00) return 'A';
    if ($gpa >= 3.50) return 'A-';
    if ($gpa >= 3.00) return 'B';
    if ($gpa >= 2.00) return 'C';
    if ($gpa >= 1.00) return 'D';
    return 'F';
}
?>

<!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="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            font-size: 12px;
            background-color: #f5f7fa;
        }
        
        .draggable-container {
            display: flex;
            gap: 20px;
            margin-top: 20px;
        }
        
        .available-subjects {
            flex: 1;
            background: #fff;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .marksheet-preview {
            flex: 2;
            background: #fff;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            min-height: 600px;
        }
        
        .subject-item {
            padding: 10px;
            margin: 5px 0;
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 5px;
            cursor: move;
            transition: all 0.2s;
        }
        
        .subject-item:hover {
            background: #bbdefb;
            transform: translateY(-2px);
        }
        
        .drop-zone {
            min-height: 50px;
            border: 2px dashed #3498db;
            border-radius: 5px;
            padding: 15px;
            margin: 10px 0;
            background: #f8f9fa;
        }
        
        .dropped-item {
            padding: 10px;
            margin: 5px 0;
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            border-radius: 5px;
            cursor: move;
        }
        
        .marksheet {
            border: 2px solid #2c3e50;
            padding: 15px;
            margin: 15px auto;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            max-width: 800px;
            position: relative;
            overflow: hidden;
        }
        
        .school-header {
            text-align: center;
            border-bottom: 2px double #3498db;
            padding-bottom: 10px;
            margin-bottom: 15px;
            background: linear-gradient(to right, #ffffff, #e3f2fd, #ffffff);
            border-radius: 6px 6px 0 0;
            margin-left: -15px;
            margin-right: -15px;
            padding-left: 15px;
            padding-right: 15px;
            position: relative;
        }
        
        .school-logo {
            width: 60px;
            height: 60px;
            border: 2px solid #3498db;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 8px;
        }
        
        .school-name {
            font-size: 24px;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 5px;
        }
        
        .school-address {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 5px;
        }
        
        .marksheet-title {
            text-align: center;
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
            margin: 10px 0;
            padding: 8px;
            background: #ecf0f1;
            border-radius: 5px;
            border: 1px solid #bdc3c7;
        }
        
        .student-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        
        .info-group {
            flex: 1;
            min-width: 200px;
            margin-bottom: 10px;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 5px;
        }
        
        .info-label {
            font-weight: 600;
            width: 120px;
            color: #2c3e50;
        }
        
        .info-value {
            flex: 1;
            color: #34495e;
        }
        
        .subjects-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            font-size: 12px;
        }
        
        .subjects-table th,
        .subjects-table td {
            border: 1px solid #bdc3c7;
            padding: 6px 4px;
            text-align: center;
        }
        
        .subjects-table th {
            background: #ecf0f1;
            font-weight: 600;
            color: #2c3e50;
        }
        
        .subjects-table td {
            background: #ffffff;
        }
        
        .subjects-table tr:nth-child(even) td {
            background: #f8f9fa;
        }
        
        .result-summary {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
            flex-wrap: wrap;
        }
        
        .signature-section {
            display: flex;
            justify-content: space-between;
            margin: 30px 0;
            flex-wrap: wrap;
        }
        
        .signature-box {
            text-align: center;
            flex: 1;
            min-width: 150px;
            margin: 0 10px;
            padding: 30px 10px 10px 10px;
            border-top: 1px solid #7f8c8d;
            color: #7f8c8d;
            font-size: 14px;
        }
        
        .grade-scale {
            text-align: center;
            padding: 10px;
            background: #ecf0f1;
            border-radius: 5px;
            margin-top: 20px;
            font-size: 12px;
            color: #2c3e50;
        }
        
        .print-button {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            body {
                background-color: #fff;
            }
            
            .marksheet {
                box-shadow: none;
                border: 1px solid #000;
            }
        }
        
        .container-fluid { max-width: 100% !important; }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4 no-print">
            <h2><i class="fas fa-file-alt"></i> কাস্টম ড্র্যাগ-এবল মার্কশীট</h2>
            <div>
                <button onclick="window.print()" class="btn btn-success me-2"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
                <a href="../index.php" class="btn btn-secondary me-2"><i class="fas fa-home"></i> হোম</a>
                <a href="custom_draggable_marksheet_complete.php" class="btn btn-primary"><i class="fas fa-search"></i> নতুন অনুসন্ধান</a>
            </div>
        </div>

        <?php if ($student && $session && $exam_type): ?>
        <!-- Success message -->
        <?php if (isset($_GET['saved']) && $_GET['saved'] == 1): ?>
        <div class="alert alert-success alert-dismissible fade show no-print" role="alert">
            <strong>সফল!</strong> লেআউট সফলভাবে সংরক্ষিত হয়েছে।
            <?php if (isset($_SESSION['default_layout']) && $_SESSION['default_layout'] == $_GET['layout']): ?>
                <div class="mt-2">এই লেআউটটি ডিফল্ট হিসেবে সেট করা হয়েছে এবং সব মার্কশীটে প্রয়োগ হবে।</div>
            <?php endif; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <!-- Default Layout Info -->
        <?php if (isset($_SESSION['default_layout'])): ?>
        <div class="alert alert-info no-print" role="alert">
            <div class="d-flex justify-content-between">
                <div>
                    <strong>ডিফল্ট লেআউট:</strong> <?php echo htmlspecialchars($_SESSION['default_layout']); ?>
                    <small class="d-block">(সব মার্কশীটে প্রয়োগ হচ্ছে)</small>
                </div>
                <form method="POST" class="d-inline">
                    <input type="hidden" name="clear_default_layout" value="1">
                    <button type="submit" class="btn btn-sm btn-outline-danger">ডিফল্ট মুছুন</button>
                </form>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Saved Layouts -->
        <?php 
        // Find all saved layouts
        $saved_layouts = [];
        foreach ($_SESSION as $key => $value) {
            if (strpos($key, 'custom_layout_') === 0) {
                $layout_name = substr($key, 13); // Remove 'custom_layout_' prefix
                $saved_layouts[] = $layout_name;
            }
        }
        ?>
        
        <?php if (!empty($saved_layouts)): ?>
        <div class="card no-print mb-3">
            <div class="card-header">
                <h5 class="mb-0">সংরক্ষিত লেআউটসমূহ</h5>
            </div>
            <div class="card-body">
                <div class="d-flex flex-wrap gap-2">
                    <?php foreach ($saved_layouts as $layout): ?>
                        <a href="?student_id=<?php echo urlencode($student_id); ?>&session=<?php echo urlencode($session); ?>&exam_type=<?php echo urlencode($exam_type); ?>&layout=<?php echo urlencode($layout); ?>" 
                           class="btn btn-outline-primary btn-sm <?php echo (isset($_GET['layout']) && $_GET['layout'] == $layout) || (isset($_SESSION['default_layout']) && $_SESSION['default_layout'] == $layout && !isset($_GET['layout'])) ? 'active' : ''; ?>">
                            <?php echo htmlspecialchars($layout); ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Draggable Interface -->
        <div class="draggable-container no-print">
            <div class="available-subjects">
                <h5>বিষয়গুলি (ড্র্যাগ করতে পারেন)</h5>
                <?php foreach ($results as $result): ?>
                <div class="subject-item" data-subject-id="<?php echo htmlspecialchars($result['subject_id']); ?>">
                    <?php echo htmlspecialchars($result['subject_name']); ?>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div class="marksheet-preview">
                <h5>মার্কশীট প্রিভিউ</h5>
                <div class="drop-zone" id="subject-drop-zone">
                    <h6>বিষয়গুলি এখানে ড্রপ করুন</h6>
                    <p>ড্র্যাগ করে বিষয়গুলির অবস্থান পরিবর্তন করুন</p>
                    <!-- Dropped subjects will appear here -->
                </div>
                
                <button class="btn btn-primary mt-3" data-bs-toggle="modal" data-bs-target="#saveLayoutModal">
                    <i class="fas fa-save"></i> লেআউট সংরক্ষণ করুন
                </button>
            </div>
        </div>
        
        <!-- Save Layout Modal -->
        <div class="modal fade" id="saveLayoutModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">লেআউট সংরক্ষণ করুন</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form method="POST">
                        <div class="modal-body">
                            <input type="hidden" name="save_layout" value="1">
                            <input type="hidden" name="student_id" value="<?php echo htmlspecialchars($student_id); ?>">
                            <input type="hidden" name="session" value="<?php echo htmlspecialchars($session); ?>">
                            <input type="hidden" name="exam_type" value="<?php echo htmlspecialchars($exam_type); ?>">
                            <input type="hidden" name="subject_order" id="subjectOrderInput" value="">
                            
                            <div class="mb-3">
                                <label for="layout_name" class="form-label">লেআউটের নাম</label>
                                <input type="text" class="form-control" id="layout_name" name="layout_name" required>
                            </div>
                            <div class="mb-3 form-check">
                                <input type="checkbox" class="form-check-input" id="set_as_default" name="set_as_default" value="1">
                                <label class="form-check-label" for="set_as_default">ডিফল্ট হিসেবে সেট করুন (সব মার্কশীটে প্রয়োগ হবে)</label>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                            <button type="submit" class="btn btn-primary">সংরক্ষণ করুন</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Marksheet Display -->
        <div class="marksheet">
            <div class="school-header">
                <?php if ($logo_image): ?>
                <div class="school-logo">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="max-width: 100%; max-height: 100%;">
                </div>
                <?php else: ?>
                <div class="school-logo">
                    <i class="fas fa-graduation-cap" style="font-size: 24px; color: #3498db;"></i>
                </div>
                <?php endif; ?>
                <div class="school-name"><?php echo htmlspecialchars($site_name); ?></div>
                <div class="school-address"><?php echo htmlspecialchars($site_address); ?></div>
            </div>
            
            <div class="marksheet-title">মার্কশীট</div>
            
            <div class="student-info">
                <div>
                    <div class="info-row">
                        <div class="info-label">শিক্ষার্থীর নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পিতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['father_name'] ?? ''); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">মাতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['mother_name'] ?? ''); ?></div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">রোল নম্বর</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['roll_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শ্রেণী</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['class_name'] . ' ' . $student['section']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">সেশন</div>
                        <div class="info-value"><?php echo htmlspecialchars($session); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পরীক্ষার ধরন</div>
                        <div class="info-value"><?php echo htmlspecialchars(ucfirst($exam_type)); ?></div>
                    </div>
                </div>
            </div>
            
            <table class="subjects-table">
                <thead>
                    <tr>
                        <th>বিষয়</th>
                        <th>সিকে</th>
                        <th>এমসিকিউ</th>
                        <th>ব্যবহারিক</th>
                        <th>অ্যাসাইনমেন্ট</th>
                        <th>উপস্থিতি</th>
                        <th>প্রাপ্ত নম্বর</th>
                        <th>পূর্ণ নম্বর</th>
                        <th>গ্রেড</th>
                        <th>গ্রেড পয়েন্ট</th>
                    </tr>
                </thead>
                <tbody id="subjectsTableBody">
                    <?php foreach ($results as $result): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($result['subject_name']); ?></td>
                        <td><?php echo number_format($result['cq_marks'], 2); ?></td>
                        <td><?php echo number_format($result['mcq_marks'], 2); ?></td>
                        <td><?php echo number_format($result['practical_marks'], 2); ?></td>
                        <td><?php echo number_format($result['assignment_marks'], 2); ?></td>
                        <td><?php echo number_format($result['attendance_marks'], 2); ?></td>
                        <td><?php echo number_format($result['marks_obtained'], 2); ?></td>
                        <td><?php echo number_format($result['full_marks'], 2); ?></td>
                        <td><?php echo htmlspecialchars($result['grade']); ?></td>
                        <td><?php echo number_format($result['grade_point'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <div class="result-summary">
                <div>
                    <div class="info-row">
                        <div class="info-label">মোট নম্বর</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo $total_obtained; ?>/<?php echo $total_marks; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শতাংশ</div>
                        <div class="info-value" style="font-weight: 700; color: #3498db;"><?php echo $percentage; ?>%</div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">গ্রেড</div>
                        <div class="info-value" style="font-weight: 700; font-size: 18px; 
                            <?php 
                            // Calculate grade based on GPA instead of percentage
                            $gpa_based_grade = calculateGradeFromGPA($gpa);
                            switch ($gpa_based_grade) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo $gpa_based_grade; ?>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">জিপিএ</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo number_format($gpa, 2); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">মেধা অবস্থান</div>
                        <div class="info-value" style="font-weight: 700; color: #e74c3c;"><?php echo $merit_position ? $merit_position : 'N/A'; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">উত্তীর্ণ বিষয়</div>
                        <div class="info-value" style="font-weight: 700; color: #27ae60;"><?php echo $passed_subjects; ?>/<?php echo $total_subjects; ?></div>
                    </div>
                </div>
            </div>
            
            <div class="signature-section">
                <div class="signature-box">পরীক্ষকের স্বাক্ষর</div>
                <div class="signature-box">প্রধান শিক্ষকের স্বাক্ষর</div>
                <div class="signature-box">অভিভাবকের স্বাক্ষর</div>
            </div>
            
            <div class="grade-scale">
                <strong>গ্রেড স্কেল:</strong> A+ (80%-100%), A (70%-79%), A- (60%-69%), B (50%-59%), C (40%-49%), D (33%-39%), F (0%-32%)
            </div>
        </div>
        <?php else: ?>
        <!-- Search form -->
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0"><i class="fas fa-search"></i> মার্কশীট অনুসন্ধান</h4>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label for="class_id" class="form-label">শ্রেণী</label>
                                <select id="class_id" name="class_id" class="form-select" required>
                                    <option value="">শ্রেণী নির্বাচন করুন</option>
                                    <?php foreach ($classes as $class_item): ?>
                                        <option value="<?php echo htmlspecialchars($class_item['id']); ?>" <?php echo ($class_id == $class_item['id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($class_item['name'] . ' ' . $class_item['section']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="session" class="form-label">সেশন</label>
                                <select id="session" name="session" class="form-select" required>
                                    <option value="">সেশন নির্বাচন করুন</option>
                                    <?php foreach ($sessions as $session_item): ?>
                                        <option value="<?php echo htmlspecialchars($session_item['session']); ?>" <?php echo ($session == $session_item['session']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($session_item['session']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="exam_type" class="form-label">পরীক্ষার ধরন</label>
                                <select id="exam_type" name="exam_type" class="form-select" required>
                                    <option value="">পরীক্ষা নির্বাচন করুন</option>
                                    <?php foreach ($exam_types as $exam_type_item): ?>
                                        <option value="<?php echo htmlspecialchars($exam_type_item['exam_type']); ?>" <?php echo ($exam_type == $exam_type_item['exam_type']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($exam_type_item['exam_type']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-12">
                                <label for="student_search" class="form-label">শিক্ষার্থী অনুসন্ধান (নাম, রোল নম্বর, আইডি)</label>
                                <input type="text" id="student_search" name="student_search" class="form-control" placeholder="শিক্ষার্থী অনুসন্ধান করুন..." value="<?php echo htmlspecialchars($student_search); ?>">
                            </div>
                            <div class="col-md-12 text-center">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-search"></i> মার্কশীট দেখুন
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php if ($show_student_list && !empty($students_in_class)): ?>
                <div class="card mt-4">
                    <div class="card-header bg-info text-white">
                        <h4 class="mb-0"><i class="fas fa-users"></i> শিক্ষার্থী তালিকা</h4>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>আইডি</th>
                                        <th>নাম</th>
                                        <th>রোল নম্বর</th>
                                        <th>কার্যক্রম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($students_in_class as $student_item): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($student_item['student_id']); ?></td>
                                        <td><?php echo htmlspecialchars($student_item['first_name'] . ' ' . $student_item['last_name']); ?></td>
                                        <td><?php echo htmlspecialchars($student_item['roll_number']); ?></td>
                                        <td>
                                            <a href="?student_id=<?php echo $student_item['id']; ?>&session=<?php echo urlencode($session); ?>&exam_type=<?php echo urlencode($exam_type); ?>" class="btn btn-sm btn-primary">
                                                <i class="fas fa-eye"></i> মার্কশীট দেখুন
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php elseif ($show_student_list): ?>
                <div class="alert alert-warning mt-4 text-center">
                    <i class="fas fa-exclamation-circle"></i> কোন শিক্ষার্থী খুঁজে পাওয়া যায়নি।
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            // Make subjects draggable
            $(".subject-item").draggable({
                helper: "clone",
                cursor: "move",
                zIndex: 9999
            });
            
            // Make drop zone droppable
            $("#subject-drop-zone").droppable({
                accept: ".subject-item",
                drop: function(event, ui) {
                    var draggedItem = ui.draggable;
                    var subjectName = draggedItem.text().trim();
                    var subjectId = draggedItem.data('subject-id');
                    
                    // Check if item is already in drop zone
                    var exists = false;
                    $("#subject-drop-zone .dropped-item").each(function() {
                        if ($(this).data('subject-id') == subjectId) {
                            exists = true;
                            return false;
                        }
                    });
                    
                    // Add to drop zone if not already there
                    if (!exists) {
                        var newItem = $('<div class="dropped-item" data-subject-id="' + subjectId + '">' + subjectName + '</div>');
                        newItem.draggable({
                            cursor: "move",
                            zIndex: 9999
                        });
                        $(this).append(newItem);
                    }
                }
            });
            
            // Handle save layout modal
            $('#saveLayoutModal').on('show.bs.modal', function () {
                var subjectOrder = [];
                $("#subject-drop-zone .dropped-item").each(function() {
                    subjectOrder.push($(this).data('subject-id'));
                });
                $("#subjectOrderInput").val(subjectOrder.join(','));
            });
        });
    </script>
</body>
</html>