<?php
session_start();
include('../login/check_flogin.php');

if (!isset($_SESSION['student_id'])) {
    header("Location: ../login/student_login.php");
    exit();
}

$con = mysqli_connect('localhost', 'root', '', 'WSAS');

// Get student data
$student_id = $_SESSION['student_id'];
$query = mysqli_query($con, "SELECT * FROM adminstudent WHERE student_id = '$student_id'");
$student = mysqli_fetch_assoc($query);

// Get enrolled subjects
$subjects_query = mysqli_query($con, "
    SELECT 
        a.subject_code,
        a.subject_name,
        (a.lecture_unit + a.lab_unit) AS units,
        sc.sc_remark
    FROM student_curriculum sc
    JOIN adminsubject a ON sc.subject_id = a.subject_id
    WHERE sc.student_id = '$student_id'
    AND sc.sc_status IN ('enrolled','completed','failed')
");

$subjects = [];

while ($row = mysqli_fetch_assoc($subjects_query)) {
    $subjects[] = $row;
}

$hasRemarks = false;

foreach ($subjects as $sub) {
    if (!empty($sub['sc_remark'])) {
        $hasRemarks = true;
        break;
    }
}

// Get current active semester info
$current_sem_query = mysqli_query($con, "
    SELECT sy_begin, sy_end, semester 
    FROM school_year 
    WHERE is_active = 1 
    LIMIT 1
");
$current_sem = mysqli_fetch_assoc($current_sem_query);

// Check if student has fully paid using the latest SOA
$payment_query = mysqli_query($con, "
    SELECT balance_fee 
    FROM soa 
    WHERE enroll_id = '$student_id'
    ORDER BY soa_date DESC
    LIMIT 1
");
$payment = mysqli_fetch_assoc($payment_query);
$isFullyPaid = ($payment && $payment['balance_fee'] <= 0);

$hasRemarks = false;
foreach ($subjects as $sub) {
    if (!empty($sub['sc_remark'])) {
        $hasRemarks = true;
        break;
    }
}
 
$canDownloadGrades = ($isFullyPaid && $hasRemarks);

// Check print status
$check_print = mysqli_query($con, "
    SELECT * FROM print_logs 
    WHERE student_id = '$student_id'
    AND semester = '{$current_sem['semester']}'
");
$hasPrinted = mysqli_num_rows($check_print) > 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Dashboard - Student </title>
    
    <link rel="shortcut icon" type="x-icon" href="../images/logo.png">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="../Style/snavstyle.css">

<style>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body{
    background: #F3F4F4;
}

.dashboard-container {
    display: flex;
    height: 100vh;
}

.mainbar {
    margin-left: 270px;
    flex: 1;
    padding: 10px;
    transition: all 0.4s ease;
    overflow-y: auto;
}

.mainbar-header {
    padding: 6px 12px;
    background-color: #3e7f31;
    border-radius: 10px;
    margin-bottom: 20px;
}

.mainbar-header h1 {
    margin: 0;
    color: white;
    font-size: 18px;
}

.container {
    background-color: #4a9c3f;
    padding: 15px;
    border-radius: 10px;
    width: 100%;
    max-width: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 40px auto;
    box-sizing: border-box;
}

.grades {
    position: relative;
    background-color: white;
    padding: 15px 15px;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    text-align: center;
    margin: 10px auto;
    max-width: 500px;
    width: 100%;
    box-sizing: border-box;
}

.grades-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 25px;
    height: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    transition: 0.3s;
    z-index: 10;
    font-size: 11px;
    font-weight: bold;
}

.grades-btn:hover {
    background-color: #43a047;
}

.grades-btn::after {
    content: "Download";
    position: absolute;
    bottom: 125%;
    left: 50%;
    transform: translateX(-50%);
    background-color: #333;
    color: #fff;
    padding: 3px 6px;
    border-radius: 5px;
    font-size: 11px;
    white-space: nowrap;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s, visibility 0.3s;
    pointer-events: none;
}

.grades-btn:hover::after {
    opacity: 1;
    visibility: visible;
}

.grades-btn::before {
    content: "";
    position: absolute;
    top: -5px;
    left: 50%;
    transform: translateX(-50%);
    border-width: 5px;
    border-style: solid;
    border-color: #333 transparent transparent transparent;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s, visibility 0.3s;
}

.grades-btn:hover::before {
    opacity: 1;
    visibility: visible;
}

.grades-btn.disabled-btn {
    background-color: gray !important;
    cursor: not-allowed;
    opacity: 0.6;
}

.grades-btn.disabled-btn:hover {
    background-color: gray !important; 
}

.grade-header h3 {
    font-size: 11px;
    margin-bottom: 3px;
}

.grade-header p {
    font-size: 11px;
    margin: 2px 0;
}

.grade-top {
    margin-top: 15px;
}

.student-details {
    text-align: left;
    margin-top: 10px;
    font-size: 11px;
}

.student-details p {
    margin: 4px 0;
}

.line {
    display: inline-block;
    width: 120px;
    border-bottom: 1px solid black;
    margin-left: 5px;
}

.grade-title {
    margin-top: 15px;
    font-size: 11px;
}

.grade-table {
    margin-top: 8px;
}

.grade-table table {
    border-collapse: collapse;
    font-family: "Segoe UI", sans-serif;
    text-align: center;
    width: 100%;
    font-size: 11px;
}

.grade-table th,
.grade-table td {
    border: 1px solid #000;
    padding: 3px 6px;
}

.grade-table th {
    font-weight: bold;
}

/* Tablet */
@media screen and (max-width: 768px) {
    .mainbar {
        margin-left: 0;
        padding: 8px;
        margin-top: 60px;
    }

    .mainbar-header {
        padding: 5px 10px;
        border-radius: 8px;
    }

    .mainbar-header h1 {
        font-size: 16px;
        text-align: center;
    }

    .container {
        padding: 15px;
        margin: 20px auto;
         max-width: 70%;
    }

    .grades {
        padding: 20px 25px;
        border-radius: 8px;
        max-width: 100%;
    }

    .grades-btn {
        width: 30px;
        height: 30px;
        top: 8px;
        right: 8px;
    }

    .grade-header h3 { 
        font-size: 10px; 
    }

    .grade-header p { 
        font-size: 10px; 
    }

    .student-details p { 
        font-size: 10px; 
    }

    .line { 
        width: 100px; 
    }

    .grade-title { 
        font-size: 10px; 
        text-align: center; 
    }

    .grade-table table { 
        font-size: 10px; 
        min-width: 350px; 
    }

    .grade-table th, .grade-table td { 
        padding: 4px 6px; 
    }
}

/* Mobile phone */
@media screen and (max-width: 576px) {
    .mainbar {
        margin-top: 50px;
        padding: 10px;
    }

    .mainbar-header {
        padding: 5px 10px;
        border-radius: 8px;
    }

    .mainbar-header h1 {
        font-size: 12px;
        text-align: center;
    }

    .container { 
        padding: 10px; 
        margin: 15px auto; 
        border-radius: 8px; 
        max-width: 65%;
    }

    .grades { 
        padding: 6px 12px; 
        border-radius: 6px; 
    }

    .grade-header h3 { 
        font-size: 8px; 
    }

    .grade-header p { 
        font-size: 8px; 
    }

    .grades-btn { 
        width: 25px; 
        height: 25px; 
        top: 5px; 
        right: 5px; 
    }

    .grades-btn::after { 
        font-size: 12px; 
        padding: 3px 6px; 
    }

    .student-details p { 
        font-size: 8px; 
    }

    .line { 
        width: 90px; 
    }
    .grade-title { 
        font-size: 8px; 
    
    }
    .grade-table table { 
        font-size: 8px; 
        min-width: 300px; 
    }

    .grade-table th, .grade-table td { 
        padding: 3px 5px; 
    }
}

/* Smaller phone */
@media screen and (max-width: 400px) {
    .mainbar { 
        margin-top: 55px; 
        padding: 8px; 
    }
    
    .mainbar-header { 
        padding: 3px 6px; 
        border-radius: 6px; 
    }
    
    .mainbar-header h1 {
        font-size: 10px;
        text-align: center; 
    }
    
    .container { 
        padding: 8px; 
        margin: 10px auto; 
        border-radius: 6px; 
        max-width: 70%; 
    }
    
    .grades { 
        padding: 3px 6px; 
        border-radius: 6px; 
        max-width: 100%; 
    }
    
    .grades-btn { 
        width: 20px; 
        height: 20px; 
        top: 5px; 
        right: 5px; 
    }
    
    .grade-header h3 { 
        font-size: 6px; 
        margin-bottom: 2px; 
    }
    
    .grade-header p { 
        font-size: 6px; 
        margin: 1px 0; 
    }
    
    .student-details p { 
        font-size: 6px; 
    }
    
    .line {
        display: inline-block;
        min-width: 50px;
        max-width: 100%;
    }
    
    .grade-title { 
        font-size: 6px; 
    }

    .grade-table {
        overflow-x: auto;
        margin-bottom: 5px;
    }
    
    .grade-table table { 
        font-size: 6px; 
        min-width: 100%;
        padding:3px
    }
}
</style>

</head>
<body>
    <!-- Side Navigation -->
    <?php include('studentnav.php'); ?>
    
    <!-- MAIN -->
    <aside class="mainbar">
        <div class="mainbar-header">
            <h1> Grades </h1>
        </div>

        <div class="container">
            <div class="grades"> 
                <button type="button" 
                    class="grades-btn <?php echo !$canDownloadGrades ? 'disabled-btn' : ''; ?>" 
                    onclick="downloadGrades()" 
                    <?php echo !$canDownloadGrades ? 'disabled' : ''; ?>>
                    <span class="material-symbols-outlined" style="vertical-align: middle; font-size: 20px;">
                        Download
                    </span>
                </button>

                <div class="grade-header">
                    <h3> COLEGIO DE LOS BAÑOS </h3>
                    <p> Lopez Avenue, Brgy. Batong Malake, </p>
                    <p> Los Baños, Laguna 4030 </p> <br>
                    <p><b> <?php echo $current_sem['semester'] . ', SY ' . $current_sem['sy_begin'] . ' - ' . $current_sem['sy_end']; ?> </b></p>
                </div> 
                
                <div class="grade-top">
                    <div class="student-details">
                        <p> Student No.: <span class="line"><?php echo $student['student_id_num']; ?></span></p>
                        <p> Name: <span class="line"> 
                            <?php 
                                echo $student['f_name'] . " " . 
                                    $student['m_name'] . " " . 
                                    $student['l_name']; 
                            ?>
                        </span></p>
                        <?php
                            $course_id = $student['course_id'];
                            $course_query = mysqli_query($con, "SELECT course_code FROM admincourse WHERE course_id = '$course_id'");
                            $course = mysqli_fetch_assoc($course_query);
                        ?>
                        <p> Course: <span class="line"><?= htmlspecialchars($course['course_code']); ?></span></p>
                    </div>
                </div>          

                <h3 class="grade-title"> Copy of Grades </h3>   
                               
                <div class="grade-table">
                    <table>
                        <tr>
                            <th> Subjects </th>
                            <th> Units </th>
                            <th> Remarks </th>
                        </tr>
                        <tbody>
                            <?php if (count($subjects) > 0): ?>
                                <?php foreach ($subjects as $sub): ?>
                                    <tr>
                                        <td style="text-align:left;">
                                            <?= htmlspecialchars($sub['subject_code'] . ' - ' . $sub['subject_name']); ?>
                                        </td>
                                        <td><?= $sub['units']; ?></td>
                                        <td>
                                            <?php
                                                if (!$isFullyPaid) {
                                                    echo "-";
                                                } else {
                                                    if (!empty($sub['sc_remark'])) {
                                                        echo ($sub['sc_remark'] === 'passed') ? "Passed" :
                                                            (($sub['sc_remark'] === 'failed') ? "Failed" : "-");
                                                    } else {
                                                        echo "-";
                                                    }
                                                }
                                            ?>
                                        </td>     
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="3">No subjects found</td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                    </table>
                </div>    
            </div>
        </div>
    </aside>

<script>
function downloadGrades() {
    if (!<?php echo json_encode($canDownloadGrades); ?>) {
        alert("You cannot download grades yet. Either you are not fully paid or grades are not finalized.");
        return;
    }

    if (hasPrinted) {
        alert("You have already downloaded this document.");
        return;
    }

    const element = document.querySelector(".grades");

    const opt = {
        margin: 10,
        filename: 'copy_of_grades.pdf',
        image: { type: 'jpeg', quality: 1 },
        html2canvas: { scale: 3, useCORS: true },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
    };

    html2pdf().set(opt).from(element).save().then(() => {
        fetch('mark_printed.php', { method: 'POST' })
        .then(() => {
            hasPrinted = true;
            const btn = document.querySelector('.grades-btn');
            btn.style.backgroundColor = 'gray';
            btn.style.cursor = 'not-allowed';
        });
    });
}
</script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

    <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
</body>
</html>