<?php
session_start();
error_reporting(0);
include '../admin/includes/database.php';
include '../admin/includes/functions.php';

$conn = new Functions();

//header('Content-Type: application/json');

if(!empty($_POST['class']) && !empty($_POST['term']) && !empty($_POST['section']) && !empty($_POST['subject'])){

    $class = $_POST['class'];
    $term = $_POST['term'];
    $section = $_POST['section'];
    $subject = $_POST['subject'];
    $exam_year = $_POST['exam_year'];

    try {
        // Get current school session
        $sql = "SELECT current_school_session FROM general_settings";
        $conn->query($sql);
        $current_school_session = $conn->fetchColumn();

        // Get assessment template for this class and term
        $sql = "SELECT at.id, at.template_name, at.total_marks,
                       ac.id as component_id, ac.component_name, ac.component_key, 
                       ac.max_marks, ac.display_order
                FROM assessment_templates at
                JOIN assessment_components ac ON at.id = ac.template_id
                WHERE at.class = :class AND at.term = :term AND at.status = 'active'
                ORDER BY ac.display_order";

        $conn->query($sql);
        $conn->bind(':class', $class);
        $conn->bind(':term', $term);
        $template_results = $conn->fetchMultiple();

        if (empty($template_results)) {
            echo json_encode(['success' => false, 'message' => "No active assessment template found for $class - $term. Please contact admin."]);
            exit;
        }

        $template = [
            'id' => $template_results[0]->id,
            'template_name' => $template_results[0]->template_name,
            'total_marks' => $template_results[0]->total_marks,
            'components' => []
        ];

        foreach ($template_results as $row) {
            $template['components'][] = [
                'id' => $row->component_id,
                'name' => $row->component_name,
                'key' => $row->component_key,
                'max_marks' => $row->max_marks,
                'display_order' => $row->display_order
            ];
        }



        // Get class ID for student lookup
        $sql = "SELECT id FROM classes WHERE name = :class_name";
        $conn->query($sql);
        $conn->bind(':class_name', $class);
        $class_id = $conn->fetchColumn();

        // Get section ID for student lookup
        $sql = "SELECT id FROM sections WHERE name = :section_name AND class =:class_id";
        $conn->query($sql);
        $conn->bind(':section_name', $section);
        $conn->bind(':class_id', $class_id);
        $section_id = $conn->fetchColumn();

        // Fetch students for the selected class and section
        $sql = "SELECT s.*, c.name as class_name FROM student s 
                JOIN classes c ON s.classesID = c.id 
                WHERE s.classesID = :class_id AND s.sectionid = :section_id 
                ORDER BY s.name";
        $conn->query($sql);
        $conn->bind(':class_id', $class_id);
        $conn->bind(':section_id', $section_id);

        $students = $conn->fetchMultiple();

        if (empty($students)) {
            echo json_encode(['success' => false, 'message' => "No students found for the selected class and section."]);
            exit;
        }

        $output = generateFlexibleMarkForm($template, $students, $class, $term, $section, $subject, $exam_year, $current_school_session, $conn);

        echo json_encode(['success' => true, 'html' => $output]);

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

} else {
    echo json_encode(['success' => false, 'message' => "All fields are required."]);
}

function generateFlexibleMarkForm($template, $students, $class, $term, $section, $subject, $exam_year, $current_school_session, $conn) {
    $output = '';

    // Header section
    $output .= '<div class="alert alert-info">';
    $output .= '<h5><i class="fas fa-info-circle"></i> Assessment Details</h5>';
    $output .= '<div class="row">';
    $output .= '<div class="col-md-3"><strong>Template:</strong> ' . htmlspecialchars($template['template_name']) . '</div>';
    $output .= '<div class="col-md-3"><strong>Class:</strong> ' . htmlspecialchars($class) . '</div>';
    $output .= '<div class="col-md-3"><strong>Term:</strong> ' . htmlspecialchars($term) . '</div>';
    $output .= '<div class="col-md-3"><strong>Subject:</strong> ' . htmlspecialchars($subject) . '</div>';
    $output .= '</div>';
    $output .= '<div class="row mt-2">';
    $output .= '<div class="col-md-6"><strong>Section:</strong> ' . htmlspecialchars($section) . '</div>';
    $output .= '<div class="col-md-6"><strong>Total Marks:</strong> ' . $template['total_marks'] . '</div>';
    $output .= '</div>';
    $output .= '</div>';

    // Form start
    $output .= '<form method="post" id="flexible-mark-form">';

    // Hidden fields
    $output .= '<input type="hidden" name="template_id" value="' . $template['id'] . '">';
    $output .= '<input type="hidden" name="class" value="' . htmlspecialchars($class) . '">';
    $output .= '<input type="hidden" name="term" value="' . htmlspecialchars($term) . '">';
    $output .= '<input type="hidden" name="section" value="' . htmlspecialchars($section) . '">';
    $output .= '<input type="hidden" name="subject" value="' . htmlspecialchars($subject) . '">';
    $output .= '<input type="hidden" name="exam_year" value="' . $exam_year . '">';
    $output .= '<input type="hidden" name="current_school_session" value="' . htmlspecialchars($current_school_session) . '">';

    // Table structure
    $output .= '<div class="table-responsive">';
    $output .= '<table class="table table-bordered table-striped">';

    // Table header
    $output .= '<thead class="bg-primary">';
    $output .= '<tr>';
    $output .= '<th>#</th>';
    $output .= '<th>Photo</th>';
    $output .= '<th>Student Name</th>';

    foreach ($template['components'] as $component) {
        $output .= '<th>' . htmlspecialchars($component['name']) . '<br><small>(' . $component['max_marks'] . ')</small></th>';
    }

    $output .= '<th>Total<br><small>(' . $template['total_marks'] . ')</small></th>';
    $output .= '<th>%</th>';
    $output .= '</tr>';
    $output .= '</thead>';

    $output .= '<tbody>';

    $count = 1;
    foreach ($students as $student) {
        $output .= '<tr class="student-row">';

        // Student number
        $output .= '<td>' . $count . '</td>';

        // Student photo
        $student_image = $student->photo;
        if (empty($student_image)) {
            $output .= '<td><img src="../admin/images/default.png" width="32" height="32" class="rounded-circle"></td>';
        } else {
            $output .= '<td><img src="../admin/upload/' . $student_image . '" width="32" height="32" class="rounded-circle"></td>';
        }

        // Student name
        $output .= '<td class="student-name">' . htmlspecialchars($student->name) . '</td>';

        // Hidden fields for student info
        $output .= '<input type="hidden" name="student_name[]" value="' . htmlspecialchars($student->name) . '">';
        $output .= '<input type="hidden" name="reg_no[]" value="' . htmlspecialchars($student->registerNO) . '">';
        $output .= '<input type="hidden" class="max-total-score" value="' . $template['total_marks'] . '">';

        // Get existing scores for this student
        $existing_scores = getExistingScores($conn, $student->name, $class, $term, $section, $subject, $current_school_session, $template['id']);

        $total_score = 0;

        // Component score inputs
        foreach ($template['components'] as $component) {
            $existing_score = isset($existing_scores[$component['id']]) ? $existing_scores[$component['id']] : '';
            $total_score += floatval($existing_score);

            $output .= '<td>';
            $output .= '<input type="number" name="scores[' . $count . '][' . $component['id'] . ']" ';
            $output .= 'class="form-control form-control-sm component-score" ';
            $output .= 'min="0" max="' . $component['max_marks'] . '" ';
            $output .= 'step="0.1" value="' . $existing_score . '" ';
            $output .= 'placeholder="0" data-component-id="' . $component['id'] . '">';
            $output .= '</td>';
        }

        // Total score display
        $output .= '<td><strong><span class="total-score-display">' . number_format($total_score, 1) . '</span></strong></td>';

        // Percentage display
        $percentage = $template['total_marks'] > 0 ? ($total_score / $template['total_marks'] * 100) : 0;
        $output .= '<td><strong><span class="percentage-display">' . number_format($percentage, 1) . '%</span></strong></td>';

        $output .= '</tr>';
        $count++;
    }

    $output .= '</tbody>';
    $output .= '</table>';
    $output .= '</div>';

    // Submit button
    $output .= '<div class="row mt-3">';
    $output .= '<div class="col-md-12">';
    $output .= '<button type="submit" class="btn btn-success btn-lg" id="save-marks-btn">';
    $output .= '<i class="fas fa-save"></i> Save All Marks';
    $output .= '</button>';
    $output .= '</div>';
    $output .= '</div>';

    $output .= '</form>';

    return $output;
}

function getExistingScores($conn, $student_name, $class, $term, $section, $subject, $school_session, $template_id) {
    $scores = [];

    try {
        // Get the student result record
        $sql = "SELECT sr.id FROM student_results sr 
                WHERE sr.student_name = :student_name 
                AND sr.class = :class 
                AND sr.term = :term 
                AND sr.section = :section 
                AND sr.subject = :subject 
                AND sr.current_school_session = :school_session 
                AND sr.template_id = :template_id";

        $conn->query($sql);
        $conn->bind(':student_name', $student_name);
        $conn->bind(':class', $class);
        $conn->bind(':term', $term);
        $conn->bind(':section', $section);
        $conn->bind(':subject', $subject);
        $conn->bind(':school_session', $school_session);
        $conn->bind(':template_id', $template_id);

        $result = $conn->fetchSingle();

        if ($result) {
            $result_id = $result->id;

            // Get component scores
            $sql = "SELECT component_id, score FROM student_assessment_scores 
                    WHERE result_id = :result_id";
            $conn->query($sql);
            $conn->bind(':result_id', $result_id);
            $score_results = $conn->fetchMultiple();

            foreach ($score_results as $score_row) {
                $scores[$score_row->component_id] = $score_row->score;
            }
        }
    } catch (Exception $e) {
        // Handle error silently, return empty scores
    }

    return $scores;
}