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

$alert = "";

// Handle multi-row POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $session_id = intval($_POST['session_id']);
    $exam_id = intval($_POST['exam_id']);
    $class_id = intval($_POST['class_id']);
    $section_id = intval($_POST['section_id']);
    
    // Check if these arrays exist
    if(isset($_POST['subject_id']) && is_array($_POST['subject_id']) && count($_POST['subject_id']) > 0) {
        $subjects = $_POST['subject_id'];
        $theory_marks = isset($_POST['full_marks_theory']) ? $_POST['full_marks_theory'] : [];
        $internal_marks = isset($_POST['full_marks_internal']) ? $_POST['full_marks_internal'] : [];
        $theory_credit = isset($_POST['theory_credit_hour']) ? $_POST['theory_credit_hour'] : [];
        $internal_credit = isset($_POST['internal_credit_hour']) ? $_POST['internal_credit_hour'] : [];
        $remarks = isset($_POST['remarks']) ? $_POST['remarks'] : [];
        
        // Get current user ID
        $user_id = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 0;
        
        // Prepare statements
        $check_stmt = $conn->prepare("SELECT id FROM exam_subject_marks WHERE session_id = ? AND exam_id = ? AND class_id = ? AND section_id = ? AND subject_id = ?");
        $insert_stmt = $conn->prepare("INSERT INTO exam_subject_marks (session_id, exam_id, class_id, section_id, subject_id, full_marks_theory, full_marks_internal, theory_credit_hour, internal_credit_hour, remarks, entered_by, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $update_stmt = $conn->prepare("UPDATE exam_subject_marks SET full_marks_theory = ?, full_marks_internal = ?, theory_credit_hour = ?, internal_credit_hour = ?, remarks = ?, updated_by = ? WHERE session_id = ? AND exam_id = ? AND class_id = ? AND section_id = ? AND subject_id = ?");
        
        $success_count = 0;
        $error_count = 0;
        $errors = [];
        
        for ($i = 0; $i < count($subjects); $i++) {
            $sid = intval($subjects[$i]);
            $t_marks = isset($theory_marks[$i]) && $theory_marks[$i] !== '' ? floatval($theory_marks[$i]) : 0.00;
            $in_marks = isset($internal_marks[$i]) && $internal_marks[$i] !== '' ? floatval($internal_marks[$i]) : 0.00;
            $t_credit = isset($theory_credit[$i]) && $theory_credit[$i] !== '' ? floatval($theory_credit[$i]) : 0.00;
            $in_credit = isset($internal_credit[$i]) && $internal_credit[$i] !== '' ? floatval($internal_credit[$i]) : 0.00;
            $rem = isset($remarks[$i]) ? $conn->real_escape_string($remarks[$i]) : '';
            
            // Validate marks
            if ($t_marks < 0 || $t_marks > 1000) {
                $errors[] = "Theory marks for subject #" . ($i+1) . " must be between 0 and 1000";
                continue;
            }
            if ($in_marks < 0 || $in_marks > 1000) {
                $errors[] = "Internal marks for subject #" . ($i+1) . " must be between 0 and 1000";
                continue;
            }
            if ($t_credit < 0 || $t_credit > 10) {
                $errors[] = "Theory credit hour for subject #" . ($i+1) . " must be between 0 and 10";
                continue;
            }
            if ($in_credit < 0 || $in_credit > 10) {
                $errors[] = "Internal credit hour for subject #" . ($i+1) . " must be between 0 and 10";
                continue;
            }
            
            // Check if record exists
            $check_stmt->bind_param("iiiii", $session_id, $exam_id, $class_id, $section_id, $sid);
            $check_stmt->execute();
            $check_stmt->store_result();
            
            if ($check_stmt->num_rows > 0) {
                // Update record
                $update_stmt->bind_param("ddddssiiiii", $t_marks, $in_marks, $t_credit, $in_credit, $rem, $user_id, $session_id, $exam_id, $class_id, $section_id, $sid);
                if($update_stmt->execute()) {
                    $success_count++;
                } else {
                    $error_count++;
                    $errors[] = "Failed to update subject #" . ($i+1) . ": " . $update_stmt->error;
                }
            } else {
                // Insert new record
                $insert_stmt->bind_param("iiiiddddssii", $session_id, $exam_id, $class_id, $section_id, $sid, $t_marks, $in_marks, $t_credit, $in_credit, $rem, $user_id, $user_id);
                if($insert_stmt->execute()) {
                    $success_count++;
                } else {
                    $error_count++;
                    $errors[] = "Failed to insert subject #" . ($i+1) . ": " . $insert_stmt->error;
                }
            }
        }
        
        $check_stmt->close();
        $insert_stmt->close();
        $update_stmt->close();
        
        if($error_count == 0 && $success_count > 0) {
            $alert = "success";
        } elseif($success_count > 0 && $error_count > 0) {
            $alert = "partial";
            // Store errors in session to display
            $_SESSION['save_errors'] = $errors;
        } else {
            $alert = "error";
            $_SESSION['save_errors'] = $errors;
        }
    } else {
        $alert = "no_subjects";
    }
}

// Fetch dropdown data
$exams = $conn->query("SELECT id, exm_year, exm_year_ad, exam_type FROM examination_type ORDER BY id DESC")->fetch_all(MYSQLI_ASSOC);
$classes = $conn->query("SELECT class_id, class FROM classes WHERE status = '1' ORDER BY class_numeric")->fetch_all(MYSQLI_ASSOC);
$sections = $conn->query("SELECT section_id, section_name FROM sections WHERE status = '1' ORDER BY section_id")->fetch_all(MYSQLI_ASSOC);
$sessions = $conn->query("SELECT year_id, ay_bs, ay_ad, status FROM academic_years ORDER BY year_id DESC")->fetch_all(MYSQLI_ASSOC);

$active_session = null;
foreach ($sessions as $sess) {
    if ($sess['status'] === 'active') {
        $active_session = $sess['year_id'];
        break;
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assign Full Marks</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/animate-css/animate.min.css">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css">
    <link rel="stylesheet" href="css/main.css">
    <style>
        .custom-button {
            color: white;
            background-color: #28a745;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
        }

        .custom-button:hover {
            color: white;
            background-color: #218838;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .subject-row {
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        
        .form-control-sm {
            height: 36px;
            padding: 5px 10px;
        }
        
        .table thead th {
            background-color: #f8f9fa;
            font-weight: 600;
            position: sticky;
            top: 0;
        }
        
        .marks-input {
            text-align: center;
            font-weight: bold;
        }
        
        .total-row {
            background-color: #e8f5e9 !important;
            font-weight: bold;
        }
        
        .subject-type-badge {
            font-size: 0.7rem;
            padding: 2px 6px;
            border-radius: 3px;
        }
        
        .type-compulsory {
            background-color: #d4edda;
            color: #155724;
        }
        
        .type-optional {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .type-elective {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .credit-input {
            width: 70px;
            text-align: center;
        }
        
        .required-field::after {
            content: " *";
            color: #dc3545;
        }
    </style>
</head>

<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <div class="content-container">
                <?php include('includes/leftbar.php'); ?>
               
                <div class="main-page">
                    <div class="container-fluid">
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title"><i class="fa fa-percentage"></i> Assign Full Marks</h2>
                            </div>
                            <div class="col-md-6 text-right">
                                <button class="custom-button" onclick="location.href='view_exam_subject_marks.php'">
                                    <i class="fa fa-eye"></i> View/Edit Marks
                                </button>
                            </div>
                        </div>

                        <div class="row breadcrumb-div">
                            <div class="col-md-12">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li>Exam Management</li>
                                    <li class="active">Assign Full Marks</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5><i class="fa fa-edit"></i> Manage Full Marks for Subjects</h5>
                                        </div>
                                    </div>

                                    <div class="panel-body">
                                        <form method="POST" id="marksForm">
                                            <div class="row">
                                                <div class="form-group col-md-3">
                                                    <label class="required-field"><i class="fa fa-calendar"></i> Academic Session</label>
                                                    <select name="session_id" class="form-control" required id="session_id">
                                                        <option value="">Select Session</option>
                                                        <?php foreach ($sessions as $s): ?>
                                                            <option value="<?= $s['year_id'] ?>" <?= $s['year_id'] == $active_session ? 'selected' : '' ?>>
                                                                <?= htmlspecialchars($s['ay_bs']) ?> - <?= htmlspecialchars($s['ay_ad']) ?>
                                                                <?= $s['status'] == 'active' ? ' (Active)' : '' ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="required-field"><i class="fa fa-file-text"></i> Examination</label>
                                                    <select name="exam_id" class="form-control" required id="exam_id">
                                                        <option value="">Select Exam</option>
                                                        <?php foreach ($exams as $ex): ?>
                                                            <option value="<?= $ex['id'] ?>">
                                                                <?= htmlspecialchars($ex['exam_type']) ?> 
                                                                (<?= htmlspecialchars($ex['exm_year']) ?>)
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="required-field"><i class="fa fa-graduation-cap"></i> Class</label>
                                                    <select name="class_id" id="class_id" class="form-control" required>
                                                        <option value="">Select Class</option>
                                                        <?php foreach ($classes as $cl): ?>
                                                            <option value="<?= $cl['class_id'] ?>">
                                                                <?= htmlspecialchars($cl['class']) ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="required-field"><i class="fa fa-users"></i> Section</label>
                                                    <select name="section_id" id="section_id" class="form-control" required>
                                                        <option value="">Select Section</option>
                                                        <?php foreach ($sections as $sec): ?>
                                                            <option value="<?= $sec['section_id'] ?>">
                                                                <?= htmlspecialchars($sec['section_name']) ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <div id="subjectTable"></div>
                                            
                                            <div class="text-right mt-4">
                                                <button type="submit" name="submit" class="btn btn-primary btn-lg">
                                                    <i class="fa fa-save"></i> Save All Marks
                                                </button>
                                                <button type="button" id="clearBtn" class="btn btn-secondary btn-lg">
                                                    <i class="fa fa-refresh"></i> Clear Form
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <script src="js/main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        $(document).ready(function() {
            // Initialize select2
            $('select').select2({
                theme: 'bootstrap',
                placeholder: 'Select an option',
                allowClear: true
            });
            
            // Function to load subjects
            function loadSubjects() {
                const classId = $('#class_id').val();
                const sectionId = $('#section_id').val();
                const sessionId = $('#session_id').val();
                const examId = $('#exam_id').val();
                
                if (classId && sectionId && sessionId && examId) {
                    // Show loading indicator
                    $('#subjectTable').html(`
                        <div class="text-center" style="padding: 40px;">
                            <i class="fa fa-spinner fa-spin fa-3x text-primary"></i>
                            <p class="mt-3">Loading subjects and marks...</p>
                        </div>
                    `);
                    
                    $.ajax({
                        url: 'ajax/get_subjects_by_class_for_marks.php',
                        method: 'POST',
                        data: { 
                            class_id: classId,
                            section_id: sectionId,
                            session_id: sessionId,
                            exam_id: examId
                        },
                        success: function(data) {
                            $('#subjectTable').html(data);
                            calculateTotals();
                            
                            // Add input event listeners for auto-calculation
                            $('input[name="full_marks_theory[]"], input[name="full_marks_internal[]"]').on('input', function() {
                                calculateTotals();
                            });
                        },
                        error: function(xhr, status, error) {
                            console.error('Error:', error);
                            $('#subjectTable').html(`
                                <div class="alert alert-danger">
                                    <i class="fa fa-exclamation-triangle"></i> 
                                    Error loading subjects. Please try again.
                                </div>
                            `);
                        }
                    });
                } else {
                    $('#subjectTable').html(`
                        <div class="alert alert-info">
                            <i class="fa fa-info-circle"></i> 
                            Please select Session, Exam, Class, and Section to view subjects.
                        </div>
                    `);
                }
            }
            
            // Function to calculate totals
            function calculateTotals() {
                let totalTheory = 0;
                let totalInternal = 0;
                let totalTheoryCredit = 0;
                let totalInternalCredit = 0;
                
                $('input[name="full_marks_theory[]"]').each(function() {
                    const val = parseFloat($(this).val()) || 0;
                    totalTheory += val;
                });
                
                $('input[name="full_marks_internal[]"]').each(function() {
                    const val = parseFloat($(this).val()) || 0;
                    totalInternal += val;
                });
                
                $('input[name="theory_credit_hour[]"]').each(function() {
                    const val = parseFloat($(this).val()) || 0;
                    totalTheoryCredit += val;
                });
                
                $('input[name="internal_credit_hour[]"]').each(function() {
                    const val = parseFloat($(this).val()) || 0;
                    totalInternalCredit += val;
                });
                
                // Update total row if exists
                if($('#totalRow').length) {
                    $('#totalRow td:nth-child(3)').text(totalTheory.toFixed(2));
                    $('#totalRow td:nth-child(4)').text(totalInternal.toFixed(2));
                    $('#totalRow td:nth-child(5)').text(totalTheoryCredit.toFixed(2));
                    $('#totalRow td:nth-child(6)').text(totalInternalCredit.toFixed(2));
                }
            }
            
            // Event listeners for dropdown changes
            $('#class_id, #section_id, #session_id, #exam_id').change(function() {
                loadSubjects();
            });
            
            // Clear form button
            $('#clearBtn').click(function() {
                Swal.fire({
                    title: 'Clear Form?',
                    text: 'This will clear all entered marks. Continue?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, clear it!',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $('input[type="text"], input[type="number"]').val('');
                        $('#subjectTable').html('');
                        calculateTotals();
                        Swal.fire('Cleared!', 'Form has been cleared.', 'success');
                    }
                });
            });
            
            // Form validation
            $('#marksForm').submit(function(e) {
                const subjectCount = $('input[name="subject_id[]"]').length;
                if (subjectCount === 0) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'No Subjects',
                        text: 'Please select a class-section combination that has subjects.',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }
                
                // Validate marks
                let isValid = true;
                let errorMessages = [];
                
                $('input[name="full_marks_theory[]"]').each(function(index) {
                    const val = parseFloat($(this).val()) || 0;
                    if (val < 0 || val > 1000) {
                        isValid = false;
                        errorMessages.push(`Theory marks for subject ${index + 1} must be between 0 and 1000`);
                    }
                });
                
                $('input[name="full_marks_internal[]"]').each(function(index) {
                    const val = parseFloat($(this).val()) || 0;
                    if (val < 0 || val > 1000) {
                        isValid = false;
                        errorMessages.push(`Internal marks for subject ${index + 1} must be between 0 and 1000`);
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        html: errorMessages.join('<br>'),
                        confirmButtonText: 'OK'
                    });
                    return false;
                }
            });

            <?php if ($alert === "success"): ?>
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    html: 'All marks have been saved successfully.',
                    timer: 3000,
                    showConfirmButton: false
                });
            <?php elseif ($alert === "partial"): ?>
                Swal.fire({
                    icon: 'warning',
                    title: 'Partial Success',
                    html: 'Some marks were saved, but there were errors:<br><small><?php 
                        if(isset($_SESSION['save_errors'])) {
                            echo implode("<br>", array_map('htmlspecialchars', $_SESSION['save_errors']));
                            unset($_SESSION['save_errors']);
                        }
                    ?></small>',
                    confirmButtonText: 'OK'
                });
            <?php elseif ($alert === "error"): ?>
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    html: 'There was an error saving the marks.<br><small><?php 
                        if(isset($_SESSION['save_errors'])) {
                            echo implode("<br>", array_map('htmlspecialchars', $_SESSION['save_errors']));
                            unset($_SESSION['save_errors']);
                        }
                    ?></small>',
                    confirmButtonText: 'OK'
                });
            <?php elseif ($alert === "no_subjects"): ?>
                Swal.fire({
                    icon: 'warning',
                    title: 'No Subjects',
                    text: 'No subjects were found to save. Please select a class-section with subjects.',
                    timer: 3000,
                    showConfirmButton: false
                });
            <?php endif; ?>
        });
    </script>

</body>

</html>