<?php
include('includes/session.php');
error_reporting(0);
// Connect to the database
include('includes/dbconnection.php');
// Fetch student ID (e.g., via GET parameter)
$student_id = $_SESSION['student_id'];


// Fetch the current term
$termQuery = "SELECT id, term_name FROM school_terms WHERE session_id = '$currentSessionId'
              AND start_date <= CURDATE() 
              AND end_date >= CURDATE() 
              ORDER BY start_date ASC 
              LIMIT 1";
$termResult = mysqli_query($con, $termQuery);
$termRow = mysqli_fetch_assoc($termResult);
$currentTermId = $termRow['id'];
$currentTermName = $termRow['term_name'];

// Handle POST selections or fallback to defaults
$session_id = $_GET['session_id'];
$term_id = $_GET['term_id'];
$class = $_GET['class'];

// Get selected names
$selected_session = mysqli_fetch_assoc(mysqli_query($con, "SELECT session_name FROM school_sessions WHERE id = '$session_id'"))['session_name'] ?? '';
$selected_term = mysqli_fetch_assoc(mysqli_query($con, "SELECT term_name FROM school_terms WHERE id = '$term_id'"))['term_name'] ?? '';

// Fetch all sessions, terms, and student's result classes
$sessions = mysqli_query($con, "SELECT * FROM school_sessions ORDER BY id DESC");
$terms = mysqli_query($con, "SELECT * FROM school_terms");
$classes = mysqli_query($con, "SELECT DISTINCT class FROM result2 WHERE student_id = '$student_id'");


// Fetch student info
$student_sql = "SELECT * FROM students WHERE id = $student_id";
$student_result = $con->query($student_sql);
$student = $student_result->fetch_assoc();
$default_class = $student['class'];
$section = $student['section'];
$student_name = htmlspecialchars($student['studentName']);
$studentImage = "studentimages/" . htmlspecialchars($student['studentImage']);


// Get selected session and term
$selected_session_id = $_GET['session_id'];
$selected_term_id = $_GET['term_id'];



// Fetch all terms for the session, ordered correctly
$terms_sql = "SELECT id AS term_id, term_name FROM school_terms WHERE session_id = '$selected_session_id' ORDER BY id ASC";
$terms_result = $con->query($terms_sql);

$terms = [];
$term_order = [];
$term_names = [];


if ($terms_result && $terms_result->num_rows > 0) {
    while ($row = $terms_result->fetch_assoc()) {
        $terms[] = $row;
        $term_order[] = $row['term_id'];
        $term_names[$row['term_id']] = $row['term_name'];
    }
}

$current_term_index = array_search($selected_term_id, $term_order);

$previous_term_ids = [];

if ($current_term_index !== false) {
    for ($i = 0; $i < $current_term_index; $i++) {
        $previous_term_ids[] = $term_order[$i];
    }
}

$all_terms_to_fetch = array_merge($previous_term_ids, [$selected_term_id]);
$term_ids_in = implode(",", $all_terms_to_fetch);


$results = [];  // Initialize it as an empty array to avoid "undefined" error
$total_score = 0;
$total_subjects = 0;
$mark_obtainable = 0;
$percentage = 0;
$average_score = 0;
$error_message = '';


// Fetch academic results

// Now use the student's class directly
        $results_sql = "SELECT term_id, subject, test_score, test_score2, class_performance, weekly_assessment, remarks_test,
                            (test_score + test_score2 + class_performance + weekly_assessment) AS total_score, 
                            remarks_test, test_absent, test2_absent, class_performance_absent, weekly_assessment_absent
                        FROM result2
                WHERE student_id = '$student_id' 
                AND session_id = '$selected_session_id' 
                AND term_id = '$selected_term_id'
                AND class = '$class'";


$results_result = $con->query($results_sql);

$subjects_results = [];
$total_score = 0;
$total_subjects = 0;
$mark_obtainable = 0;
$percentage = 0;
$average_score = 0;
$error_message = '';

if ($results_result && $results_result->num_rows > 0) {
    while ($row = $results_result->fetch_assoc()) {
        $subjects_results[] = $row;
    }

    $total_subjects = count($subjects_results);
    $mark_obtainable = $total_subjects * 30;

    foreach ($subjects_results as $result) {
        $total_score += $result['total_score'] ?? 0;
    }

    $percentage = $total_subjects ? round(($total_score / $mark_obtainable) * 100, 2) : 0;
    $average_score = $total_subjects ? round($total_score / $total_subjects, 2) : 0;
} else {
    $error_message = "No results found for this student.";
}
// Remark generator
function generateRemark($percentage)
{
    if ($percentage >= 75) {
        return 'Outstanding Performance!';
    } elseif ($percentage >= 60) {
        return 'Commendable performance!';
    } elseif ($percentage >= 50) {
        return 'Satisfactory Performance!';
    } elseif ($percentage >= 40) {
        return 'Marginal Performance!';
    } else {
        return 'Unsatisfactory Performance!';
    }
}
$principal_remarks = generateRemark($percentage);

use Mpdf\Mpdf;
use Dotenv\Dotenv;

// 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'];



// Start HTML buffer
ob_start();
?>

<!DOCTYPE html>
<html>

<head>
    <style>
        .header {
            padding-top: 20px;
            text-align: center;
            font-family: 'Times New Roman', Times, serif;
            /* Good size for print readability */
            font-weight: bold;
            /* Optional: makes it more prominent */
        }

        .logo {
            float: left;
            margin-right: 20px;
        }

        .school-name {
            float: right;
        }



        .report-title {
            font-size: 14px;
            font-weight: bold;
            background-color: #ff0000;
            color: white;
            padding: 5px;
            text-align: center;
            width: fit-content;
            margin: 10px auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th,
        td {
            border: 1px solid #000;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .comment-section,
        .signature-section {
            margin-top: 20px;
        }

        .line {
            border-bottom: 1px solid #000;
            margin: 5px 0;
        }

        .print-btn {
            margin: 20px 0;
        }
    </style>
</head>

<body>


    <table width="100%" border = "0" style="border-collapse: collapse; font-family: 'Times New Roman', Times, serif; font-size: 12px;">
        <tr>
            <!-- Logo: right side -->
            <td style="text-align: left; vertical-align: top; width: 10%; border:none;">
                <img src="<?php echo $logo; ?>" width="100" alt="logo">
            </td>
            <!-- School Name: left side, but centered internally -->
            <td style="text-align: center; width: 90%; border:none">
                <h1 class="mb-0 fw-bold" style="font-weight:bold; font-size: 36px;"><?php echo strtoupper($school_name) ?></h1>
                <?php echo $address; ?><br>
                <b>Website:</b> <span><?php echo $website; ?></span>
                <b> | E-mail:</b> <span><?php echo $school_email; ?></span>
            </td>


        </tr>
    </table>
    <div style="text-align: center; font-weight: bold; font-size: 18px; margin: 10px 0;">
        MID-TERM REPORT
    </div>

    <hr style="border: 1px solid #000; margin: 5px 0;">
    <div class="card-body">
        <!-- Student Bio -->
        <table style="border-collapse: collapse; border: none; width: 100%; font-size: 12px; text-align: left;">
            <tr>
                <td style="border: none; max-width: 100px;"><strong>NAME:</strong> <?php echo htmlspecialchars($student_name); ?></td>
                <td style="border: none; max-width: 100px;"><strong>CLASS:</strong> <?php echo htmlspecialchars($class); ?> - <?php echo htmlspecialchars($section); ?></td>
                <td style="border: none; max-width: 100px;"><strong>TERM:</strong> <?php echo htmlspecialchars($selected_term); ?></td>            
                <td style="border: none; max-width: 100px;"><strong>SESSION:</strong> <?php echo htmlspecialchars($selected_session); ?></td>
            </tr>
        </table>
<table style="font-size:12px; text-align:center; width:100%; border-collapse:collapse; table-layout:fixed;">
    <thead>
        <tr>
            <th style="font-style: italic; width:25%;">Subject</th>
            <th style="font-style: italic; text-align: center; width:15%;">1st C.A. Test</th>
            <th style="font-style: italic; text-align: center; width:15%;">2nd C.A. Test</th>
            <th style="font-style: italic; text-align: center; width:15%;">Ass/Exe</th>
            <th style="font-style: italic; text-align: center; width:15%;">Total</th>
            <th style="font-style: italic; text-align: center; width:15%;">Grade</th>
        </tr>
    </thead>
    <tbody>
                <?php if (!empty($subjects_results)) : ?>
                                                        <?php foreach ($subjects_results as $result) : ?>
                                       <?php
    // Determine each score display
  // Determine individual scores
$test_score = ($result['test_absent'] == "1") ? 'AB' : (int)$result['test_score'];
$test_score2 = ($result['test2_absent'] == "1") ? 'AB' : (int)$result['test_score2'];
$class_performance = ($result['class_performance_absent'] == "1") ? 'AB' : (int)$result['class_performance'];
$weekly_assessment = ($result['weekly_assessment_absent'] == "1") ? 'AB' : (int)$result['weekly_assessment'];

// Calculate Ass/Exe
if ($class_performance === 'AB' && $weekly_assessment === 'AB') {
    $ass_exe = 'AB'; // both absent
} elseif ($class_performance === 'AB') {
    $ass_exe = $weekly_assessment; // only class performance absent
} elseif ($weekly_assessment === 'AB') {
    $ass_exe = $class_performance; // only weekly assessment absent
} else {
    $ass_exe = $class_performance + $weekly_assessment; // both present
}

// Calculate Total (sum only numeric scores)
$total = 0;
foreach ([$test_score, $test_score2, $ass_exe] as $score) {
    if (is_numeric($score)) $total += $score;
}

// Determine grade
$grade = '-';
if ($total > 0) {
    if ($total >= 25) $grade = 'Excellent';
    elseif ($total >= 20) $grade = 'Very Good';
    elseif ($total >= 15) $grade = 'Good';
    elseif ($total >= 10) $grade = 'Pass';
    else $grade = 'Fair';
}
    ?>
                        <tr>
                            <td><?php echo htmlspecialchars($result['subject']); ?></td>
                            <td style="text-align: center;"><?php echo htmlspecialchars($test_score); ?></td>
                            <td style="text-align: center;"><?php echo htmlspecialchars($test_score2); ?></td>
                            <td style="text-align: center;"><?php echo htmlspecialchars($ass_exe); ?></td>
                            <td style="text-align: center;"><?php echo htmlspecialchars($total); ?></td>
                            <td style="text-align: center;"><?php echo $grade; ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr>
                        <td colspan="6" style="text-align: center;">No results found.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <table style="width: 100%; margin-top: 20px; border-collapse: collapse; border: none; font-size:12px;">
            <tr>
                <td style="padding: 10px; border: none; width: 100%;">
                    <label for="class-teacher-comment"><strong>Class Teacher's Comment:</strong></label>
                                                <span><?= htmlspecialchars($result['remarks_test']) ?></span>
                </td>
                </tr>
            <tr>
                <td style="padding: 10px; border: none; width: 100%;">
                    <label for="class-teacher-comment"><strong>Principal's Comment:</strong></label>
                    <span><?= htmlspecialchars($principal_remarks) ?></span>
                </td>
            </tr>
        </table>


</body>

</html>

<?php
$html = ob_get_clean();

$mpdf = new Mpdf();

// ✅ Watermark Setup
// Set Watermark Image
$mpdf->SetWatermarkText('Not for Official Use', 0.1); // Text and opacity
$mpdf->showWatermarkText = true;                      // Enable it
$mpdf->watermarkTextAlpha = 0.1;                      // Faint (0.1 = very transparent)
$mpdf->watermark_font = 'DejaVuSans';                 // Ensure font is supported


$mpdf->WriteHTML($html);
$mpdf->Output('test_result.pdf', 'D');
