<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];


// Include PHPMailer and QR code libraries
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;
use Mpdf\Mpdf;  

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

// Load Composer dependencies
require_once 'vendor/autoload.php';
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$school_name = $_ENV['SCHOOL_NAME_1'] ?? '';
$logo        = $_ENV['WEBSITE_LOGO'] ?? '';
$address     = $_ENV['id_address'] ?? '';
$school_email= $_ENV['SCHOOL_EMAIL'] ?? '';
$signature   = $_ENV['PRINCIPAL_SIGNATURE'] ?? '';
$website     = $_ENV['SCHOOL_WEBSITE'] ?? '';

$SMTP_HOST   = $_ENV['SMTP_HOST'] ?? '';
$SMTP_USER   = $_ENV['SMTP_USERNAME'] ?? '';
$SMTP_PASS   = $_ENV['SMTP_PASSWORD'] ?? '';
$SMTP_PORT   = $_ENV['SMTP_PORT'];

// Fetch all students for dropdown
$students_query  = "SELECT id, studentName, studentno, email, class, section, studentImage FROM students ORDER BY studentName";
$students_result = $con->query($students_query);

// Fetch all sessions
$sessions_query  = "SELECT DISTINCT id, session_name FROM school_sessions ORDER BY session_name DESC";
$sessions_result = $con->query($sessions_query);

// Fetch all terms
$terms_query     = "SELECT DISTINCT id, term_name FROM school_terms ORDER BY id";
$terms_result    = $con->query($terms_query);

// Reusable: rebuild sessions/terms result sets when needed
function fetchAllAssoc($mysqli_result) {
    $rows = [];
    if ($mysqli_result) {
        $mysqli_result->data_seek(0);
        while ($row = $mysqli_result->fetch_assoc()) $rows[] = $row;
    }
    return $rows;
}
$sessions_list = fetchAllAssoc($sessions_result);
$terms_list    = fetchAllAssoc($terms_result);

// Initialize variables
$selected_student = $_POST['student_id'] ?? '';
$selected_session = $_POST['session_id'] ?? '';
$selected_term    = $_POST['term_id'] ?? '';
$selected_class   = $_POST['class'] ?? '';
$selected_section = $_POST['section'] ?? '';

$student_data    = [];
$grouped_results = []; // Changed from $results_data to $grouped_results for better organization
$psychomotor_data= [];
$affective_data  = [];
$attendance_percentage = null;
$overall_average = 0;
$mail_feedback   = null;

// Get session/term names
$selected_session_name = '';
$selected_term_name    = '';
if (!empty($selected_session)) {
    $row = mysqli_fetch_assoc(mysqli_query($con, "SELECT session_name FROM school_sessions WHERE id = '".mysqli_real_escape_string($con, $selected_session)."'"));
    $selected_session_name = $row['session_name'] ?? '';
}
if (!empty($selected_term)) {
    $row = mysqli_fetch_assoc(mysqli_query($con, "SELECT term_name FROM school_terms WHERE id = '".mysqli_real_escape_string($con, $selected_term)."'"));
    $selected_term_name = $row['term_name'] ?? '';
}

// Process on any action that needs transcript data
$actionTriggered = ($_SERVER['REQUEST_METHOD'] === 'POST') && (
    isset($_POST['generate_transcript']) ||
    isset($_POST['download_pdf']) ||
    isset($_POST['export_excel']) ||
    isset($_POST['send_mail'])
);

if ($actionTriggered && !empty($selected_student)) {
    // Fetch student
    $stmt = $con->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->bind_param("i", $selected_student);
    $stmt->execute();
    $student_result = $stmt->get_result();
    $student_data   = $student_result->fetch_assoc();

    // Build dynamic results query with optional filters
    $q = "SELECT r.*, s.session_name, t.term_name 
          FROM result2 r 
          LEFT JOIN school_sessions s ON r.session_id = s.id 
          LEFT JOIN school_terms t ON r.term_id = t.id 
          WHERE r.student_id = ?";
    $types = "i";
    $params = [$selected_student];

    if (!empty($selected_session)) { 
        $q .= " AND r.session_id = ?"; 
        $types .= "i"; 
        $params[] = $selected_session; 
    }
    if (!empty($selected_term)) { 
        $q .= " AND r.term_id = ?"; 
        $types .= "i"; 
        $params[] = $selected_term; 
    }
    if (!empty($selected_class)) { 
        $q .= " AND r.class = ?"; 
        $types .= "s"; 
        $params[] = $selected_class; 
    }
    if (!empty($selected_section)) { 
        $q .= " AND r.section = ?"; 
        $types .= "s"; 
        $params[] = $selected_section; 
    }

    $q .= " ORDER BY s.session_name, t.term_name, r.subject";
    $stmt = $con->prepare($q);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $results_result = $stmt->get_result();
    
    // Group results by session and term
    $grouped_results = [];
    while ($row = $results_result->fetch_assoc()) {
        $session_id = $row['session_id'];
        $term_id = $row['term_id'];
        
        if (!isset($grouped_results[$session_id])) {
            $grouped_results[$session_id] = [
                'session_name' => $row['session_name'],
                'terms' => []
            ];
        }
        
        if (!isset($grouped_results[$session_id]['terms'][$term_id])) {
            $grouped_results[$session_id]['terms'][$term_id] = [
                'term_name' => $row['term_name'],
                'results' => []
            ];
        }
        
        $grouped_results[$session_id]['terms'][$term_id]['results'][] = $row;
    }
    
    // Calculate overall average across all fetched results
    $total_score = 0;
    $subject_count = 0;
    
    foreach ($grouped_results as $session) {
        foreach ($session['terms'] as $term) {
            foreach ($term['results'] as $result) {
                $total = null;
                if ($total === null) {
                    $total = ($result['test_score'] ?? 0) + ($result['test_score2'] ?? 0) + 
                             ($result['class_performance'] ?? 0) + ($result['weekly_assessment'] ?? 0);
                }
                $total_score += $total;
                $subject_count++;
            }
        }
    }
    
    $max_score_per_subject = 30;
    $overall_average = ($subject_count > 0) 
    ? round(($total_score / ($subject_count * $max_score_per_subject)) * 100, 2) 
    : 0;


   // Psychomotor & Affective - Calculate averages
if (!empty($selected_session_name)) {
    // If only session is selected (no specific term), calculate averages across all terms in that session
    if (empty($selected_term_name)) {
        // Get psychomotor averages for the whole session
        $stmt = $con->prepare("SELECT 
            AVG(handwriting) as handwriting,
            AVG(fluency) as fluency,
            AVG(sports) as sports,
            AVG(lab_workshops) as lab_workshops
            FROM psychomotor 
            WHERE student_id = ? AND session = ?");
        $stmt->bind_param("is", $selected_student, $selected_session_name);
        $stmt->execute();
        $psychomotor_data = $stmt->get_result()->fetch_assoc() ?: [];

        // Get affective averages for the whole session
        $stmt = $con->prepare("SELECT 
            AVG(punctuality) as punctuality,
            AVG(reliability) as reliability,
            AVG(politeness_honesty) as politeness_honesty,
            AVG(self_control) as self_control
            FROM affective 
            WHERE student_id = ? AND session = ?");
        $stmt->bind_param("is", $selected_student, $selected_session_name);
        $stmt->execute();
        $affective_data = $stmt->get_result()->fetch_assoc() ?: [];
    } else {
        // Specific term selected - get data for that term only
        $stmt = $con->prepare("SELECT * FROM psychomotor 
            WHERE student_id = ? AND session = ? AND term = ? LIMIT 1");
        $stmt->bind_param("iss", $selected_student, $selected_session_name, $selected_term_name);
        $stmt->execute();
        $psychomotor_data = $stmt->get_result()->fetch_assoc() ?: [];

        $stmt = $con->prepare("SELECT * FROM affective 
            WHERE student_id = ? AND session = ? AND term = ? LIMIT 1");
        $stmt->bind_param("iss", $selected_student, $selected_session_name, $selected_term_name);
        $stmt->execute();
        $affective_data = $stmt->get_result()->fetch_assoc() ?: [];
    }
} else {
    // No session selected â†’ "All Session" â†’ average across ALL sessions and terms
    $stmt = $con->prepare("SELECT 
        AVG(handwriting) as handwriting,
        AVG(fluency) as fluency,
        AVG(sports) as sports,
        AVG(lab_workshops) as lab_workshops
        FROM psychomotor 
        WHERE student_id = ?");
    $stmt->bind_param("i", $selected_student);
    $stmt->execute();
    $psychomotor_data = $stmt->get_result()->fetch_assoc() ?: [];

    $stmt = $con->prepare("SELECT 
        AVG(punctuality) as punctuality,
        AVG(reliability) as reliability,
        AVG(politeness_honesty) as politeness_honesty,
        AVG(self_control) as self_control
        FROM affective 
        WHERE student_id = ?");
    $stmt->bind_param("i", $selected_student);
    $stmt->execute();
    $affective_data = $stmt->get_result()->fetch_assoc() ?: [];
}

// Attendance calculation
if (!empty($selected_session)) {
    if (!empty($selected_term)) {
        // Specific term selected
        $stmt = $con->prepare("SELECT COUNT(*) as present_days 
            FROM attendance 
            WHERE student_id = ? AND session_id = ? AND term_id = ? AND status = 'Present'");
        $stmt->bind_param("iii", $selected_student, $selected_session, $selected_term);
        $stmt->execute();
        $attendance_result = $stmt->get_result()->fetch_assoc();
        $present_days = intval($attendance_result['present_days'] ?? 0);

        // Total days in that term
        $stmt = $con->prepare("SELECT COUNT(DISTINCT date) as total_days 
            FROM attendance 
            WHERE session_id = ? AND term_id = ?");
        $stmt->bind_param("ii", $selected_session, $selected_term);
        $stmt->execute();
        $total_days_result = $stmt->get_result()->fetch_assoc();
        $total_days = intval($total_days_result['total_days'] ?? 0);

        $attendance_percentage = ($total_days > 0) ? round(($present_days / $total_days) * 100, 2) : 0;

    } else {
        // Only session selected - calculate attendance across all terms in the session
        $stmt = $con->prepare("SELECT COUNT(*) as present_days 
            FROM attendance 
            WHERE student_id = ? AND session_id = ? AND status = 'Present'");
        $stmt->bind_param("ii", $selected_student, $selected_session);
        $stmt->execute();
        $attendance_result = $stmt->get_result()->fetch_assoc();
        $present_days = intval($attendance_result['present_days'] ?? 0);
        
        $stmt = $con->prepare("SELECT COUNT(DISTINCT date) as total_days 
            FROM attendance 
            WHERE session_id = ?");
        $stmt->bind_param("i", $selected_session);
        $stmt->execute();
        $total_days_result = $stmt->get_result()->fetch_assoc();
        $total_days = intval($total_days_result['total_days'] ?? 0);
        
        $attendance_percentage = ($total_days > 0) ? round(($present_days / $total_days) * 100, 2) : 0;
    }
} else {
    // No session selected â†’ "All Session" â†’ calculate across ALL sessions & terms
    $stmt = $con->prepare("SELECT COUNT(*) as present_days 
        FROM attendance 
        WHERE student_id = ? AND status = 'Present'");
    $stmt->bind_param("i", $selected_student);
    $stmt->execute();
    $attendance_result = $stmt->get_result()->fetch_assoc();
    $present_days = intval($attendance_result['present_days'] ?? 0);

    $stmt = $con->prepare("SELECT COUNT(DISTINCT date) as total_days 
        FROM attendance");
    $stmt->execute();
    $total_days_result = $stmt->get_result()->fetch_assoc();
    $total_days = intval($total_days_result['total_days'] ?? 0);

    $attendance_percentage = ($total_days > 0) ? round(($present_days / $total_days) * 100, 2) : 0;
}


// Calculate class position (weighted by number of subjects, counting DISTINCT subjects)
$class = $student_data['class'];
$section = $student_data['section'];

if (!empty($selected_session)) {
    if (!empty($selected_term)) {
        // Specific term selected
        $class_position_query = "SELECT student_id, 
                                    SUM(total_score) / COUNT(DISTINCT subject) as weighted_avg
                                FROM result2 
                                WHERE session_id = ? AND term_id = ? AND class = ? AND section = ?
                                GROUP BY student_id 
                                ORDER BY weighted_avg DESC";
        $stmt = $con->prepare($class_position_query);
        $stmt->bind_param("iiss", $selected_session, $selected_term, $class, $section);
    } else {
        // Whole session (all terms in the session)
        $class_position_query = "SELECT student_id, 
                                    SUM(total_score) / COUNT(DISTINCT subject) as weighted_avg
                                FROM result2 
                                WHERE session_id = ? AND class = ? AND section = ?
                                GROUP BY student_id 
                                ORDER BY weighted_avg DESC";
        $stmt = $con->prepare($class_position_query);
        $stmt->bind_param("iss", $selected_session, $class, $section);
    }
} else {
    // All sessions (no session selected)
    $class_position_query = "SELECT student_id, 
                                SUM(total_score) / COUNT(DISTINCT subject) as weighted_avg
                            FROM result2 
                            WHERE class = ? AND section = ?
                            GROUP BY student_id 
                            ORDER BY weighted_avg DESC";
    $stmt = $con->prepare($class_position_query);
    $stmt->bind_param("ss", $class, $section);
}

$stmt->execute();
$position_result = $stmt->get_result();

$positions = [];
$rank = 0;
while ($row = $position_result->fetch_assoc()) {
    $positions[$row['student_id']] = ++$rank;
}

$class_position = isset($positions[$selected_student]) ? $positions[$selected_student] : 'N/A';


// Function to build transcript HTML
function buildTranscriptHTML($school_name, $logo, $address, $school_email, $website, $signature, $student_data, $grouped_results, $overall_average, $attendance_percentage, $selected_session_name, $selected_term_name, $class_position) {
    $studentName   = htmlspecialchars($student_data['studentName'] ?? 'N/A');
    $studentNo     = htmlspecialchars($student_data['studentno'] ?? 'N/A');
    $stuClass      = htmlspecialchars(($student_data['class'] ?? 'N/A').(isset($student_data['section'])&&$student_data['section']!=='' ? ' - '.$student_data['section'] : ''));
    $sessionName   = htmlspecialchars($selected_session_name ?: 'All Sessions');
    $termName      = htmlspecialchars($selected_term_name ?: 'All Terms');
    $attendanceTxt = ($attendance_percentage === null) ? 'N/A' : ($attendance_percentage.'%');

    // Header
    $html = '
    <div style="text-align:center; margin-bottom: 20px;">
        '.(!empty($logo) ? '<img src="'.htmlspecialchars($logo).'" height="80" style="object-fit:contain" />' : '').'
        <h1 style="margin:10px 0 5px 0;">'.strtoupper(htmlspecialchars($school_name)).'</h1>
        <div style="margin:4px 0;">'.htmlspecialchars($address).'</div>
        <div style="margin:4px 0;">Email: '.htmlspecialchars($school_email).' | Website: '.htmlspecialchars($website).'</div>
        <hr style="border-top: 2px solid #000">
    </div>';

    // Transcript title
    $html .= '<h3 style="text-align:center; margin-bottom: 20px; text-transform: uppercase;">STUDENT MID TERM ACADEMIC TRANSCRIPT</h3>';

    // Student summary
    $html .= '
    <table width="100%" cellpadding="6" cellspacing="0" style="font-size:14px; margin-bottom:20px; border: 1px solid #000; border-collapse: collapse;">
        <tr>
            <td width="25%" style="border: 1px solid #000; padding: 8px;"><strong>Student Name:</strong></td>
            <td width="25%" style="border: 1px solid #000; padding: 8px;">'.$studentName.'</td>
            <td width="25%" style="border: 1px solid #000; padding: 8px;"><strong>Admission No:</strong></td>
            <td width="25%" style="border: 1px solid #000; padding: 8px;">'.$studentNo.'</td>
        </tr>
        <tr>
            <td style="border: 1px solid #000; padding: 8px;"><strong>Class/Arm:</strong></td>
            <td style="border: 1px solid #000; padding: 8px;">'.$stuClass.'</td>
            <td style="border: 1px solid #000; padding: 8px;"><strong>Session/Term:</strong></td>
            <td style="border: 1px solid #000; padding: 8px;">'.$sessionName.' / '.$termName.'</td>
        </tr>
    </table>';

    // Results section
    $html .= '<h4 style="margin:20px 0 10px 0;">Academic Performance</h4>';
    
    if (empty($grouped_results)) {
        $html .= '<p>No academic records found for the selected filters.</p>';
    } else {
        foreach ($grouped_results as $session_id => $session_data) {
            $session_name = htmlspecialchars($session_data['session_name']);
            
            foreach ($session_data['terms'] as $term_id => $term_data) {
                $term_name = htmlspecialchars($term_data['term_name']);
                
                $html .= '
                <div style="margin: 25px 0; border: 1px solid #000; border-radius: 5px; padding: 10px;">
                    <h5 style="margin: 0 0 15px 0; padding-bottom: 8px; border-bottom: 1px solid #000;">
                        ' . $session_name . ' - ' . $term_name . '
                    </h5>
                    <table width="100%" border="1" cellpadding="8" cellspacing="0" style="border-collapse:collapse; font-size:12px;">
                        <thead>
                            <tr style="background:#f2f2f2;">
                                <th align="left">Subject</th>
                                <th align="center">1st C.A. Test</th>
                                <th align="center">2nd C.A. Test</th>
                                <th align="center">Ass/Exe</th>
                                <th align="center">Total</th>
                                <th align="center">Grade</th>
                            </tr>
                        </thead>
                        <tbody>';
                
                foreach ($term_data['results'] as $r) {
                    $t1 = !empty($r['test_absent']) ? 'AB' : intval($r['test_score'] ?? 0);
                    $t2 = !empty($r['test2_absent']) ? 'AB' : intval($r['test_score2'] ?? 0);
                    $cp = !empty($r['class_performance_absent']) ? 'AB' : intval($r['class_performance'] ?? 0);
                    $wa = !empty($r['weekly_assessment_absent']) ? 'AB' : intval($r['weekly_assessment'] ?? 0);

                                        $ass =(is_numeric($cp)?$cp:0) + (is_numeric($wa)?$wa:0);

                    $computedTotal = (is_numeric($t1)?$t1:0) + (is_numeric($t2)?$t2:0) + 
                                    (is_numeric($cp)?$cp:0) + (is_numeric($wa)?$wa:0);
                    $total = intval($r['total_score'] ?? $computedTotal);


                    $grade = getGrade($total, $student_data['class'] ?? '');
                    $html .= '<tr>
                        <td>'.htmlspecialchars($r['subject']).'</td>
                        <td align="center">'.$t1.'</td>
                        <td align="center">'.$t2.'</td>
                        <td align="center">'.$ass.'</td>
                        <td align="center"><strong>'.$total.'</strong></td>
                        <td>'.$grade.'</td>
                    </tr>';
                }
                
                $html .= '</tbody></table></div>';
            }
        }
    }

    // General remarks and signature
    $html .= '<div style="margin-top:30px;">
        <h4 style="margin:0 0 10px 0;">General Remarks</h4>
        <p style="font-style: italic;">'.getGeneralRemarks($overall_average).'</p>
    </div>';


function generateStamp($school_name, $selected_session_name) {
    $width  = 400;
    $height = 400;

    // Always pre-calc integer centers (GD expects ints)
    $centerW = (int) round($width / 2);
    $centerH = (int) round($height / 2);

    $img = imagecreatetruecolor($width, $height);

    // Colors
    $white = imagecolorallocate($img, 255, 255, 255);
    $black = imagecolorallocate($img, 0, 0, 0);
    $red   = imagecolorallocate($img, 200, 0, 0);
    $blue  = imagecolorallocate($img, 0, 102, 204);

    // Transparent background
    imagefilledrectangle($img, 0, 0, $width, $height, $white);
    imagecolortransparent($img, $white);

    // Outer circles
    imagearc($img, $centerW, $centerH, $width - 10, $height - 10, 0, 360, $blue);
    imagearc($img, $centerW, $centerH, $width - 30, $height - 30, 0, 360, $blue);
    imagearc($img, $centerW, $centerH, $width - 60, $height - 60, 0, 360, $blue);

    // Radial lines
    for ($i = 0; $i < 360; $i += 15) {
        $x1 = (int) round($centerW + (($width - 20) / 2) * cos(deg2rad($i)));
        $y1 = (int) round($centerH + (($height - 20) / 2) * sin(deg2rad($i)));
        $x2 = (int) round($centerW + (($width - 30) / 2) * cos(deg2rad($i)));
        $y2 = (int) round($centerH + (($height - 30) / 2) * sin(deg2rad($i)));
        imageline($img, $x1, $y1, $x2, $y2, $blue);
    }

    // Decorative dots
    for ($i = 0; $i < 360; $i += 10) {
        $x = (int) round($centerW + (($width - 60) / 2) * cos(deg2rad($i)));
        $y = (int) round($centerH + (($height - 60) / 2) * sin(deg2rad($i)));
        imagefilledellipse($img, $x, $y, 3, 3, $blue);
    }

    // Central circle
    imagefilledellipse($img, $centerW, 110, 30, 30, $blue);

    // Star
    $centerX = $centerW;
    $centerY = 110;
    imagefilledpolygon($img, [
        $centerX,     $centerY - 10,
        $centerX - 5, $centerY,
        $centerX - 2, $centerY + 8,
        $centerX + 2, $centerY + 8,
        $centerX + 5, $centerY
    ], 5, $white);

    // Bottom arcs
    imagearc($img, $centerW - 50, $centerH + 30, 100, 100, 0, 180, $blue);
    imagearc($img, $centerW + 50, $centerH + 30, 100, 100, 0, 180, $blue);

    // Font path
    $font = realpath(__DIR__ . "/vendor/mpdf/mpdf/ttfonts/DejaVuSans-Bold.ttf");
    if (!$font || !file_exists($font)) {
        $font = realpath(__DIR__ . "/../../fonts/DejaVuSans-Bold.ttf");
        if (!$font || !file_exists($font)) {
            $font = null;
        }
    }

    // Text rendering
    if ($font) {
        $school_lines = explode(" ", $school_name, 2);

        // Line 1
        $box1 = imagettfbbox(20, 0, $font, $school_lines[0]);
        $x1   = (int) round($centerW - (($box1[2] - $box1[0]) / 2));
        imagettftext($img, 20, 0, $x1, $centerH - 30, $black, $font, $school_lines[0]);

        // Line 2
        if (isset($school_lines[1])) {
            $box2 = imagettfbbox(20, 0, $font, $school_lines[1]);
            $x2   = (int) round($centerW - (($box2[2] - $box2[0]) / 2));
            imagettftext($img, 20, 0, $x2, $centerH + 10, $black, $font, $school_lines[1]);
        }

        // Session
        $sessionText = $selected_session_name
            ? $selected_session_name . " Academic Year"
            : "All Academic Year";

        $box3 = imagettfbbox(16, 0, $font, $sessionText);
        $x3   = (int) round($centerW - (($box3[2] - $box3[0]) / 2));
        imagettftext($img, 16, 0, $x3, $centerH + 60, $black, $font, $sessionText);

        // Date
        $dateText = "Date: " . date("M d, Y");
        $box4 = imagettfbbox(14, 0, $font, $dateText);
        $x4   = (int) round($centerW - (($box4[2] - $box4[0]) / 2));
        imagettftext($img, 14, 0, $x4, $centerH + 100, $black, $font, $dateText);
    }

    // Output
    ob_start();
    imagepng($img);
    $imageData = ob_get_clean();
    imagedestroy($img);

    return 'data:image/png;base64,' . base64_encode($imageData);
}
$stampBase64 = generateStamp($school_name, $selected_session_name);

$html .= '
<div style="margin-top:40px; text-align:center;">
    <img src="' . $stampBase64 . '" width="200" style="border-radius: 50%;" />
</div>';


    return $html;
}


    // 1) Download PDF
if (isset($_POST['download_pdf'])) {
    $recipient = $_POST['recipientwatermark'];
    $html = buildTranscriptHTML(
        $school_name, 
        $logo, 
        $address, 
        $school_email, 
        $website, 
        $signature, 
        $student_data, 
        $grouped_results, 
        $overall_average, 
        $attendance_percentage, 
        $selected_session_name, 
        $selected_term_name, 
        $class_position
    );

    $mpdf = new \Mpdf\Mpdf(['tempDir' => __DIR__ . '/tmp']);

    // âœ… Add watermark
    $mpdf->SetWatermarkText('For '.$recipient. ' Only');
    $mpdf->showWatermarkText = true;
    $mpdf->watermarkTextAlpha = 0.1; // transparency (0.1 = very light, 0.5 = darker)
    $mpdf->watermark_font = 'DejaVuSansCondensed'; // optional: controls watermark font

    $mpdf->WriteHTML($html);

    $filename = 'Transcript_' . $student_data['studentno'] . '_' . date('Ymd_His') . '.pdf';
    $mpdf->Output($filename, 'D'); // 'D' = force download
    exit;
}


    // 2) Export Excel
    if (isset($_POST['export_excel'])) {
        $filename = 'Transcript_'.$student_data['studentno'].'_'.date('Ymd_His').'.xls';
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Pragma: no-cache");
        header("Expires: 0");

        $html = buildTranscriptHTML($school_name, $logo, $address, $school_email, $website, $signature, $student_data, $grouped_results, $overall_average, $attendance_percentage, $selected_session_name, $selected_term_name, $class_position);
        echo $html;
        exit;
    }

    // 3) Send to Email
    if (isset($_POST['send_mail'])) {
        $recipient = $_POST['recipientEmail'];
            $watermark = $_POST['recipientwatermark'];
        $html = buildTranscriptHTML($school_name, $logo, $address, $school_email, $website, $signature, $student_data, $grouped_results, $overall_average, $attendance_percentage, $selected_session_name, $selected_term_name, $class_position);
        $mpdf = new Mpdf(['tempDir' => __DIR__.'/tmp']);
            // âœ… Add watermark
    $mpdf->SetWatermarkText('For '.$watermark. ' Only');
    $mpdf->showWatermarkText = true;
    $mpdf->watermarkTextAlpha = 0.1; // transparency (0.1 = very light, 0.5 = darker)
    $mpdf->watermark_font = 'DejaVuSansCondensed'; // optional: controls watermark font
        $mpdf->WriteHTML($html);
        $pdfContent = $mpdf->Output('', 'S');

        try {
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host       = $SMTP_HOST;
            $mail->SMTPAuth   = true;
            $mail->Username   = $SMTP_USER;
            $mail->Password   = $SMTP_PASS;
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = $SMTP_PORT;
            $mail->Timeout = 10;

            $mail->setFrom($school_email ?: $SMTP_USER, $school_name ?: 'School');
            $toEmail = $recipient;
            $mail->addAddress($toEmail, $student_data['studentName'] ?? 'Student');

            $mail->isHTML(true);
            $mail->Subject = "Transcript - ".($student_data['studentName'] ?? '');
            $mail->Body = '
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>Transcript Notification</title>
            </head>
            <body style="font-family: Arial, sans-serif; line-height:1.6; color:#333; background-color:#f9f9f9; padding:20px;">
                <div style="max-width:600px; margin:auto; background:#ffffff; border-radius:8px; padding:20px; box-shadow:0 2px 6px rgba(0,0,0,0.1);">
                
                <h2 style="color:#2c3e50; text-align:center; margin-bottom:20px;">Transcript Notification</h2>
                
                <p>Dear <strong>' . htmlspecialchars($student_data['studentName'] ?? 'Student') . '</strong>,</p>
                
                <p>Please find attached your transcript for your records.</p>
                
                <p style="margin-top:30px;">Best regards,<br>
                <strong>' . htmlspecialchars($school_name) . '</strong></p>
                
                <hr style="border:none; border-top:1px solid #ddd; margin:30px 0;">
                <p style="font-size:12px; color:#777; text-align:center;">
                    This is an automated message, please do not reply directly.
                </p>
                </div>
            </body>
            </html>';

            $mail->AltBody = "Dear " . ($student_data['studentName'] ?? 'Student') . ",\n\nPlease find attached your transcript.\n\nRegards,\n" . $school_name;


            $filename = 'Transcript_'.$student_data['studentno'].'_'.date('Ymd_His').'.pdf';
            $mail->addStringAttachment($pdfContent, $filename, 'base64', 'application/pdf');

            $mail->send();
            $mail_feedback = ['type'=>'success','msg'=>'Transcript sent successfully to '.$toEmail.'.'];
        } catch (Exception $e) {
            $mail_feedback = ['type'=>'danger','msg'=>'Failed to send transcript: '.$mail->ErrorInfo];
        }
    }
}
?>

<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>
<style>
    :root {
        --primary-color: #0d6efd;
        --secondary-color: #f5f5f5;
        --accent-color: #ff4081;
    }
    
    .card {
        border-radius: 10px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
        border: none;
    }
    
    .card-header {
        background-color: var(--primary-color);
        color: white;
        border-radius: 10px 10px 0 0 !important;
        padding: 15px 20px;
        font-weight: 600;
    }
    
    .btn-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }
    
    .btn-primary:hover {
        background-color: #303f9f;
        border-color: #303f9f;
    }
    
    .btn-download {
        background-color: #4caf50;
        border-color: #4caf50;
        color: white;
    }
    
    .btn-download:hover {
        background-color: #388e3c;
        border-color: #388e3c;
        color: white;
    }
    
    .btn-info {
        background-color: #17a2b8;
        border-color: #17a2b8;
        color: white;
    }
    
    .btn-info:hover {
        background-color: #138496;
        border-color: #138496;
        color: white;
    }
    
    .btn-danger {
        background-color: #dc3545;
        border-color: #dc3545;
        color: white;
    }
    
    .btn-danger:hover {
        background-color: #c82333;
        border-color: #c82333;
        color: white;
    }
    
    .filter-section {
        background-color: var(--secondary-color);
        padding: 15px;
        border-radius: 8px;
        margin-bottom: 20px;
    }
    
    .student-info {
        background: linear-gradient(135deg, #0d6efd 0%, #5a8deee6 100%);
        color: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
    
    .stats-box {
        text-align: center;
        padding: 15px;
        border-radius: 8px;
        margin-bottom: 15px;
        background-color: white;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    .stats-box i {
        font-size: 24px;
        margin-bottom: 10px;
        color: var(--primary-color);
    }
    
    .stats-box h4 {
        font-weight: 700;
        color: var(--primary-color);
    }
    
    .table-responsive {
        border-radius: 8px;
        overflow: hidden;
    }
    
    table {
        border-collapse: separate;
        border-spacing: 0;
        width: 100%;
    }
    
    th {
        background-color: var(--primary-color);
        color: white;
        font-weight: 500;
        padding: 12px 15px;
    }
    
    td {
        padding: 12px 15px;
        border-bottom: 1px solid #e0e0e0;
    }
    
    tr:nth-child(even) {
        background-color: #f5f5f5;
    }
    
    tr:hover {
        background-color: #e8eaf6;
    }
    
    .action-buttons .btn {
        margin-right: 5px;
        margin-bottom: 5px;
    }
    
    .page-title {
        color: var(--primary-color);
        font-weight: 700;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid var(--primary-color);
    }
    
    .print-only {
        display: none;
    }
    
    .school-header {
        text-align: center;
        margin-bottom: 20px;
        padding: 15px;
        border-bottom: 2px solid #0d6efd;
    }
    
    .school-header img {
        height: 80px;
        margin-bottom: 10px;
    }
    
    .school-header h2 {
        margin: 0;
        color: #0d6efd;
        font-weight: 700;
    }
    
    .school-header p {
        margin: 5px 0;
        color: #555;
    }
    
    .transcript-title {
        text-align: center;
        margin: 20px 0;
        color: #0d6efd;
        font-weight: 700;
        text-transform: uppercase;
        border-bottom: 2px solid #0d6efd;
        padding-bottom: 10px;
    }
    
    @media print {
        body * {
            visibility: hidden;
        }
        .transcript-container, .transcript-container * {
            visibility: visible;
        }
        .transcript-container {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
        }
        .no-print {
            display: none !important;
        }
        .print-only {
            display: block;
        }
        .school-header {
            border: none;
        }
    }
    
    .filter-status {
        padding: 10px;
        margin-bottom: 15px;
        border-radius: 5px;
        background-color: #e9ecef;
    }
    
    .filter-status span {
        font-weight: 600;
        color: #0d6efd;
    }
    
    .term-table {
        margin-bottom: 30px;
        border: 2px solid #0d6efd;
        border-radius: 8px;
        overflow: hidden;
    }
    
    .term-header {
        background-color: #0d6efd;
        color: white;
        padding: 10px 15px;
        font-weight: 600;
        font-size: 18px;
    }
    
    @media (max-width: 768px) {
        .stats-box {
            margin-bottom: 15px;
        }
        .action-buttons .btn {
            margin-bottom: 10px;
        }
    }
</style>
<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">
        <?php @include("includes/header.php"); ?>
        <?php @include("includes/sidebar.php"); ?>

        <div class="content-wrapper">
<section class="content-header premium-header">
    <div class="container-fluid">
        <div class="header-glass-card">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="title-section">
                        <div class="icon-box bg-primary-gradient shadow-sm">
                            <i class="fas fa-graduation-cap"></i>
                        </div>
                        <div>
                            <h1 class="premium-title text-primary">
                                Student Transcript Management
                                <span class="premium-subtitle text-secondary">Manage Transcript</span>
                            </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb premium-breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Generate Transcript</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</section>  
            
            <section class="content">
                <div class="container-fluid">
                    <?php if (!empty($mail_feedback)): ?>
                        <div class="alert alert-<?php echo $mail_feedback['type']; ?>">
                            <?php echo htmlspecialchars($mail_feedback['msg']); ?>
                        </div>
                    <?php endif; ?>
                    
                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-primary text-white">
                            <h3 class="card-title font-weight-bold">
                                <i class="fas fa-filter"></i> Transcript Filter Options
                            </h3>
                            <div class="card-tools"></div>
                        </div>
                        <div class="card-body">
                            <form method="POST" action="" id="transcriptForm">
                                <div class="row p-0 m-0">
                                    <div class="form-group col-md-4">
                                        <label>Student Name</label>
                                        <select class="form-control select2" id="studentSelect" name="student_id" required>
                                            <option value="">-- Select Student --</option>
                                            <?php 
                                            if ($students_result) {
                                                $students_result->data_seek(0);
                                                while ($student = $students_result->fetch_assoc()):
                                                    $sel = ($selected_student == $student['id']) ? 'selected' : '';
                                            ?>
                                                <option value="<?php echo $student['id']; ?>" <?php echo $sel; ?>>
                                                    <?php echo htmlspecialchars($student['studentName'] . ' (' . $student['studentno'] . ')'); ?>
                                                </option>
                                            <?php endwhile; } ?>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group col-md-4">
                                        <label>Class (optional)</label>
                                        <select id="classSelector" name="class" class="form-control select2">
                                            <option value="">---Select Class---</option>
                                            <?php
                                            $classResult = $con->query("SELECT DISTINCT class FROM class_section ORDER by class");
                                                while ($row = $classResult->fetch_assoc()) {
                                                    $selectedc = ($row['class'] == $selected_class) ? "selected" : "";
                                                    echo "<option value='".htmlspecialchars($row['class'])."' $selectedc>"
                                                        .htmlspecialchars($row['class'])."</option>";
                                                }

                                            ?>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group col-md-4">
                                        <label>Arm (optional)</label>
                                        <select id="sectionSelector" name="section" class="form-control select2">
                                            <option value="">---Select Arm</option>
                                            <?php
                                            $secRes = $con->query("SELECT DISTINCT section FROM class_section");
                                            while ($secRes && $sec = $secRes->fetch_assoc()) {
                                                $selected = ($sec['section'] == $selected_section) ? "selected" : "";
                                                echo "<option value='".htmlspecialchars($sec['section'])."' $selected>".htmlspecialchars($sec['section'])."</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group col-md-4">
                                        <label>Session (optional)</label>
                                        <select class="form-control select2" id="sessionSelect" name="session_id">
                                            <option value="">---Select Session---</option>
                                            <?php foreach ($sessions_list as $session): ?>
                                                <option value="<?php echo $session['id']; ?>" <?php echo ($selected_session == $session['id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($session['session_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group col-md-4">
                                        <label>Term (optional)</label>
                                        <select class="form-control select2" id="termSelect" name="term_id">
                                            <option value="">---Select Term---</option>
                                            <?php foreach ($terms_list as $term): ?>
                                                <option value="<?php echo $term['id']; ?>" <?php echo ($selected_term == $term['id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($term['term_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="row mt-3">
                                    <div class="col-md-12 text-center">
                                        <button type="submit" name="generate_transcript" class="btn btn-primary me-2">
                                            <i class="fas fa-search"></i> View Transcript
                                        </button>
                                        <button type="button" class="btn btn-download" onclick="window.print()">
                                            <i class="fas fa-print"></i> Print Transcript
                                        </button>
                                        <button type="button" class="btn btn-info" id="selectAllFilters">
                                            <i class="fas fa-check-square"></i> Select All Filters
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <?php if ($actionTriggered && !empty($student_data)): ?>
                    <section class="content">
                        <div class="container-fluid transcript-container">
                            <!-- School Header -->
                            <div class="school-header print-only">
                                <?php if (!empty($logo)): ?>
                                    <img src="<?php echo htmlspecialchars($logo); ?>" alt="School Logo">
                                <?php endif; ?>
                                <h2><?php echo htmlspecialchars($school_name); ?></h2>
                                <p><?php echo htmlspecialchars($address); ?></p>
                                <p>Email: <?php echo htmlspecialchars($school_email); ?> | Website: <?php echo htmlspecialchars($website); ?></p>
                            </div>
                            
                            <div class="transcript-title">
                                <h3>STUDENT MID TERM ACADEMIC TRANSCRIPT</h3>
                            </div>
                            
                            <!-- Filter Status -->
                            <div class="filter-status no-print">
                                <p>Showing transcript for: 
                                    <span>Student: <?php echo htmlspecialchars($student_data['studentName']); ?></span> | 
                                    <span>Session: <?php echo htmlspecialchars($selected_session_name ?: 'All Sessions'); ?></span> | 
                                    <span>Term: <?php echo htmlspecialchars($selected_term_name ?: 'All Terms'); ?></span>
                                </p>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="student-info">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <h3><?php echo htmlspecialchars($student_data['studentName']); ?></h3>
                                                <p class="mb-1">Admission No: <?php echo htmlspecialchars($student_data['studentno'] ?? 'N/A'); ?></p>
                                                <p class="mb-1">Class: <?php echo htmlspecialchars($student_data['class'] . ' - ' . $student_data['section']); ?></p>
                                                <p class="mb-0">Academic Session: <?php echo htmlspecialchars($selected_session_name ?: 'All Sessions'); ?></p>
                                                <p class="mb-0">Term: <?php echo htmlspecialchars($selected_term_name ?: 'All Terms'); ?></p>
                                            </div>
                                            <div class="col-md-4 text-end">
                                                <?php if (!empty($student_data['studentImage'])): ?>
                                                    <img src="studentimages/<?php echo htmlspecialchars($student_data['studentImage']); ?>" class="rounded-circle" width="100" height="100" alt="Student Image">
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-3">
                                    <div class="stats-box">
                                        <i class="fas fa-chart-line"></i>
                                        <h4><?php echo $overall_average; ?>%</h4>
                                        <p>Overall Average</p>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stats-box">
                                        <i class="fas fa-trophy"></i>
                                        <h4>N/A</h4>
                                        <p>Class Position</p>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stats-box">
                                        <i class="fas fa-check-circle"></i>
                                        <h4>N/A</h4>
                                        <p>Attendance Rate</p>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stats-box">
                                        <i class="fas fa-book"></i>
                                         <h4><?php echo $subject_count; ?></h4>
                                        <p>Subjects Taken</p>
                                    </div>
                                </div>
                            </div>

                            <?php if (!empty($grouped_results)): ?>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5 class="mb-0"><i class="fas fa-table"></i> Academic Performance</h5>
                                        </div>
                                        <div class="card-body">
                                            <?php foreach ($grouped_results as $session_id => $session_data): ?>
                                                <?php foreach ($session_data['terms'] as $term_id => $term_data): ?>
                                                    <div class="term-table">
                                                        <div class="term-header">
                                                            <?php echo htmlspecialchars($session_data['session_name']); ?> - <?php echo htmlspecialchars($term_data['term_name']); ?>
                                                        </div>
                                                        <div class="table-responsive">
                                                            <table class="table">
                                                                <thead>
                                                                    <tr>
                                                                        <th>Subject</th>
                                                                        <th>1st C.A Test</th>
                                                                        <th>2nd C.A Test</th>
                                                                        <th>Ass/Exe.</th>
                                                                        <th>Total</th>
                                                                        <th>Grade</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    <?php foreach ($term_data['results'] as $result): ?>
                                                                        <?php
                                                                        $t1 = !empty($result['test_absent']) ? 'AB' : ($result['test_score'] ?? 0);
                                                                        $t2 = !empty($result['test2_absent']) ? 'AB' : ($result['test_score2'] ?? 0);
                                                                        $cp = !empty($result['class_performance_absent']) ? 'AB' : ($result['class_performance'] ?? 0);
                                                                        $wa = !empty($result['weekly_assessment_absent']) ? 'AB' : ($result['weekly_assessment'] ?? 0);
                                                                        $ex = !empty($result['exam_absent']) ? 'AB' : ($result['exam_score'] ?? 0);
                                                                        $computedTotal = (is_numeric($t1)?$t1:0) + (is_numeric($t2)?$t2:0) + (is_numeric($cp)?$cp:0) + (is_numeric($wa)?$wa:0);
                                                                        $computedTotalass = (is_numeric($cp)?$cp:0) + (is_numeric($wa)?$wa:0);

                                                                        $total = $computedTotal;
                                                                        $grade = getGrade($total, $student_data['class']);
                                                                        ?>
                                                                        <tr>
                                                                            <td><?php echo htmlspecialchars($result['subject']); ?></td>
                                                                            <td><?php echo $t1; ?></td>
                                                                            <td><?php echo $t2; ?></td>
                                                                            <td><?php echo $computedTotalass; ?></td>
                                                                            <td><strong><?php echo $total; ?></strong></td>
                                                                            <td><strong><?php echo $grade; ?></strong></td>
                                                                        </tr>
                                                                    <?php endforeach; ?>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row mt-4">
                                <div class="col-md-12">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5 class="mb-0"><i class="fas fa-sticky-note"></i> General Remarks</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <p><?php echo getGeneralRemarks($overall_average); ?></p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

<div class="row mt-4 no-print">
    <div class="col-md-12 text-center">
        <form method="POST" action="">
            <input type="hidden" name="student_id" value="<?php echo htmlspecialchars($selected_student); ?>">
            <input type="hidden" name="class" value="<?php echo htmlspecialchars($selected_class); ?>">
            <input type="hidden" name="section" value="<?php echo htmlspecialchars($selected_section); ?>">
            <input type="hidden" name="session_id" value="<?php echo htmlspecialchars($selected_session); ?>">
            <input type="hidden" name="term_id" value="<?php echo htmlspecialchars($selected_term); ?>">

            <div class="btn-group action-buttons">
                <button type="button" id="showWatermarkForm" class="btn btn-danger">
                    <i class="fas fa-file-pdf"></i> Download PDF
                </button>
                <button type="submit" name="export_excel" class="btn btn-success">
                    <i class="fas fa-file-excel"></i> Export to Excel
                </button>
                
                <!-- Trigger button -->
                <button type="button" id="showEmailForm" class="btn btn-primary">
                    <i class="fas fa-envelope"></i> Send to Email
                </button>
            </div>

<!-- Hidden Email Form -->
<form method="POST">
    <div id="emailForm" class="fade-in mt-3" style="max-width:450px; margin:auto; display:none;">
        <div class="mb-3">
            <input type="email" name="recipientEmail" id="recipientEmail" placeholder="Enter recipient email" class="form-control" required>
        </div>
        <div class="mb-3">
            <input type="text" name="recipientwatermark" id="recipientwatermark" placeholder="Watermark Text" class="form-control" required>
        </div>
        <div class="text-center">
            <button type="submit" name="send_mail" class="btn btn-info">
                <i class="fas fa-paper-plane"></i> Send to Email
            </button>
        </div>
    </div>
</form>

<!-- Hidden Watermark Form -->
<form method="POST">
<div id="watermarkForm" class="fade-in mt-3" style="max-width:450px; margin:auto; display:none;">
    <div class="mb-3">
        <input type="text" name="recipientwatermark" id="recipientwatermark" placeholder="Watermark Text" class="form-control">
    </div>
    <div class="text-center">
        <button type="submit" name="download_pdf" class="btn btn-danger">
            <i class="fas fa-file-pdf"></i> Download PDF
        </button>
    </div>
</div>
</form>

        </form>
    </div>
</div>

<style>
/* Fade-in effect */
.fade-in {
    opacity: 0;
    transition: opacity 0.5s ease-in-out;
}
.fade-in.show {
    display: block !important;
    opacity: 1;
}
</style>

<script>
function showForm(triggerId, formId) {
    document.getElementById(triggerId).addEventListener("click", function(){
        let form = document.getElementById(formId);
        form.style.display = "block";
        setTimeout(() => form.classList.add("show"), 10);
        this.style.display = "none";
    });
}

showForm("showEmailForm", "emailForm");
showForm("showWatermarkForm", "watermarkForm");
</script>


<br>

                            <?php else: ?>
                            <div class="row mt-4">
                                <div class="col-md-12">
                                    <div class="alert alert-warning">
                                        <h4><i class="fas fa-exclamation-triangle"></i> No Data Found</h4>
                                        <p>No transcript data found for the selected criteria. Please try different filters.</p>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </section>
                    <?php endif; ?>
                </div>
            </section>
        </div>

        <?php @include("includes/foot.php"); ?>
        <?php @include("includes/footer.php"); ?>

        <script src="dist/js/select2.min.js"></script>
    

        <script>
            document.addEventListener('DOMContentLoaded', function() {
                $('.select2').select2();
                
                // Select all filters button functionality
                document.getElementById('selectAllFilters').addEventListener('click', function() {
                    const studentSelect = document.getElementById('studentSelect');
                    const sessionSelect = document.getElementById('sessionSelect');
                    const termSelect = document.getElementById('termSelect');
                    
                    if (studentSelect.options.length > 1) studentSelect.selectedIndex = 1;
                    if (sessionSelect.options.length > 1) sessionSelect.selectedIndex = 1;
                    if (termSelect.options.length > 1) termSelect.selectedIndex = 1;
                    
                    // Trigger change event for Select2
                    $(studentSelect).trigger('change');
                    $(sessionSelect).trigger('change');
                    $(termSelect).trigger('change');
                });
            });
        </script>
    </div>
</body>
</html>

<?php
// ===== Helper Functions =====
function getGrade($score, $class) {
    if (strpos($class, 'JSS') !== false) {
        if ($score >= 25) return 'Excellent';
        if ($score >= 20) return 'Very Good';
        if ($score >= 15) return 'Good';
        if ($score >= 10) return 'Pass';
        return 'Fair';
    } elseif (strpos($class, 'SS') !== false) {
        if ($score >= 25) return 'Excellent';
        if ($score >= 20) return 'Very Good';
        if ($score >= 15) return 'Good';
        if ($score >= 10) return 'Pass';
        return 'Fair';
    } else {
        if ($score >= 25) return 'Excellent';
        if ($score >= 20) return 'Very Good';
        if ($score >= 15) return 'Good';
        if ($score >= 10) return 'Pass';
        return 'Fair';
    }
}

function getGradeRemarks($grade) {
    if (in_array($grade, ['Excellent'])) return 'Excellent';
    if (in_array($grade, ['Very Good'])) return 'Very Good';
    if (in_array($grade, ['Good'])) return 'Good';
    if ($grade === 'Fair' || $grade === 'Fair') return 'Needs Improvement';
    return 'Satisfactory';
}


function getGeneralRemarks($average) {
    if ($average >= 80) return 'An exceptional student with outstanding performance across all subjects. Shows great leadership qualities and consistently exceeds expectations.';
    if ($average >= 70) return 'A very good student with strong academic performance. Demonstrates good understanding of concepts and applies knowledge effectively.';
    if ($average >= 60) return 'A satisfactory performer with consistent effort. Shows improvement potential with more focus on challenging areas.';
    if ($average >= 50) return 'Average performance with room for improvement. Would benefit from additional practice and revision of core concepts.';
    return 'Needs significant improvement. Requires additional support and regular practice to achieve expected learning outcomes.';
}
?>
