<?php
// File: fetch-broadsheet-students.php
session_start();
error_reporting(0);
include 'includes/database.php';
include 'includes/functions.php';

$conn = new Functions();
//header('Content-Type: application/json');

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

    $class = trim($_POST['class']);
    $term = trim($_POST['term']);
    $section = trim($_POST['section']);
    $session = trim($_POST['session']);

    try {
        // Fetch students who have results for the selected criteria
        $sql = "SELECT DISTINCT sr.student_name, sr.reg_no, s.photo
                FROM student_results sr
                LEFT JOIN student s ON sr.student_name = s.name
                WHERE sr.class = :class 
                AND sr.term = :term 
                AND sr.section = :section 
                AND sr.current_school_session = :session
                AND sr.total_score > 0
                ORDER BY sr.student_name ASC";

        $conn->query($sql);
        $conn->bind(':class', $class);
        $conn->bind(':term', $term);
        $conn->bind(':section', $section);
        $conn->bind(':session', $session);

        $students = $conn->fetchMultiple();

        if (empty($students)) {
            echo json_encode([
                'success' => false,
                'message' => "No students found with results for the selected criteria. Please ensure marks have been entered for this class, term, and section."
            ]);
            exit;
        }

        // Get count of subjects for this class/term/section
        $sql = "SELECT COUNT(DISTINCT subject) as subject_count
                FROM student_results
                WHERE class = :class 
                AND term = :term 
                AND section = :section 
                AND current_school_session = :session
                AND total_score > 0";

        $conn->query($sql);
        $conn->bind(':class', $class);
        $conn->bind(':term', $term);
        $conn->bind(':section', $section);
        $conn->bind(':session', $session);
        $subject_info = $conn->fetchSingle();
        $subject_count = $subject_info ? $subject_info->subject_count : 0;

        $output = generateStudentsPreview($students, $class, $term, $section, $session, $subject_count, $conn);

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

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

} else {
    echo json_encode(['success' => false, 'message' => "All fields are required. Please fill in Class, Term, Section, and School Session."]);
}

function generateStudentsPreview($students, $class, $term, $section, $session, $subject_count, $conn) {
    $base_url = $conn->base_url();
    $output = '';

    // Header section with summary
    $output .= '<div class="alert alert-info">';
    $output .= '<h5><i class="fas fa-info-circle"></i> Broadsheet Information</h5>';
    $output .= '<div class="row">';
    $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>Section:</strong> ' . htmlspecialchars($section) . '</div>';
    $output .= '<div class="col-md-3"><strong>Session:</strong> ' . htmlspecialchars($session) . '</div>';
    $output .= '</div>';
    $output .= '<div class="row mt-2">';
    $output .= '<div class="col-md-6"><strong>Total Students:</strong> <span class="badge badge-primary">' . count($students) . '</span></div>';
    $output .= '<div class="col-md-6"><strong>Subjects Offered:</strong> <span class="badge badge-success">' . $subject_count . '</span></div>';
    $output .= '</div>';
    $output .= '</div>';

    // Students table
    $output .= '<div class="table-responsive">';
    $output .= '<table class="table table-bordered table-striped table-hover">';
    $output .= '<thead class="thead-dark">';
    $output .= '<tr>';
    $output .= '<th style="width: 50px;">#</th>';
    $output .= '<th style="width: 80px;">Photo</th>';
    $output .= '<th>Student Name</th>';
    $output .= '<th style="width: 150px;">Reg No</th>';
    $output .= '</tr>';
    $output .= '</thead>';
    $output .= '<tbody>';

    $count = 1;
    foreach ($students as $student) {
        $student_image = $student->photo;
        if (empty($student_image)) {
            $img_url = $base_url . 'images/default.png';
        } else {
            $img_url = $base_url . 'upload/' . $student_image;
        }

        $output .= '<tr>';
        $output .= '<td class="text-center">' . $count . '</td>';
        $output .= '<td class="text-center"><img src="' . $img_url . '" width="50" height="50" class="rounded-circle border"></td>';
        $output .= '<td>' . htmlspecialchars($student->student_name) . '</td>';
        $output .= '<td class="text-center">' . htmlspecialchars($student->reg_no) . '</td>';
        $output .= '</tr>';
        $count++;
    }

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

    // Generate button with better styling
    $output .= '<div class="row mt-4 mb-3">';
    $output .= '<div class="col-md-12 text-center">';
    $output .= '<p class="text-muted mb-3"><i class="fas fa-info-circle"></i> The broadsheet will be generated in A3 Landscape format with all subjects displayed.</p>';
    $output .= '<button type="button" class="btn btn-danger btn-lg shadow" id="generateBroadsheetBtn">';
    $output .= '<i class="fas fa-file-pdf"></i> Generate Broadsheet PDF';
    $output .= '</button>';
    $output .= '</div>';
    $output .= '</div>';

    return $output;
}
?>