<?php

declare(strict_types=1);

require_once __DIR__ . '/../library/auth.php';

allow_roles(['admin', 'teacher']);

require_once __DIR__ . '/../vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$school_id          = (int) $_SESSION['school_id'];

$current_session_id = (int) get_current_session_id($pdo);

// ======================================================
// INPUTS
// ======================================================

$class_id = (int) ($_GET['class_id'] ?? 0);

$month = trim(
    $_GET['month'] ?? date('Y-m')
);

// ======================================================
// VALIDATION
// ======================================================

if ($class_id <= 0) {

    die('Invalid class.');
}

if (
    !preg_match(
        '/^\d{4}-\d{2}$/',
        $month
    )
) {

    die('Invalid month.');
}

// ======================================================
// DATE RANGE
// ======================================================

$start_date = $month . '-01';

$end_date = date(
    'Y-m-t',
    strtotime($start_date)
);

// ======================================================
// SCHOOL
// ======================================================

$stmt = $pdo->prepare("
    SELECT school_name

    FROM school_settings

    WHERE school_id = ?

    LIMIT 1
");

$stmt->execute([$school_id]);

$school = $stmt->fetch(PDO::FETCH_ASSOC);

// ======================================================
// CLASS
// ======================================================

$stmt = $pdo->prepare("
    SELECT class_name

    FROM classes

    WHERE id = ?
    AND school_id = ?

    LIMIT 1
");

$stmt->execute([

    $class_id,
    $school_id

]);

$class = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$class) {

    die('Class not found.');
}

// ======================================================
// HOLIDAYS
// ======================================================

$stmt = $pdo->prepare("
    SELECT holiday_date

    FROM holidays

    WHERE school_id = ?
    AND holiday_date
    BETWEEN ? AND ?
");

$stmt->execute([

    $school_id,
    $start_date,
    $end_date

]);

$holidays = array_column(

    $stmt->fetchAll(PDO::FETCH_ASSOC),

    'holiday_date'

);

// ======================================================
// WEEKLY OFFS
// ======================================================

$stmt = $pdo->prepare("
    SELECT day_name

    FROM weekly_offs

    WHERE school_id = ?
");

$stmt->execute([$school_id]);

$weekly_offs = array_column(

    $stmt->fetchAll(PDO::FETCH_ASSOC),

    'day_name'

);

// ======================================================
// WORKING DAYS
// ======================================================

$working_days = 0;

$current = strtotime($start_date);

$last = strtotime($end_date);

while ($current <= $last) {

    $date = date('Y-m-d', $current);

    $day_name = date('l', $current);

    if (
        !in_array($date, $holidays, true) &&
        !in_array($day_name, $weekly_offs, true)
    ) {

        $working_days++;
    }

    $current = strtotime('+1 day', $current);
}

// ======================================================
// STUDENTS
// ======================================================

$stmt = $pdo->prepare("
    SELECT

        ss.id AS student_session_id,

        s.name,

        ss.roll_no,

        ss.section

    FROM student_sessions ss

    INNER JOIN students s
        ON s.id = ss.student_id

    WHERE ss.school_id = ?
    AND ss.session_id = ?
    AND ss.class_id = ?
    AND ss.status = 'Active'

    ORDER BY

        CAST(ss.roll_no AS UNSIGNED) ASC,

        s.name ASC
");

$stmt->execute([

    $school_id,
    $current_session_id,
    $class_id

]);

$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ======================================================
// HTML
// ======================================================

$html = '
<style>

body{
    font-family: DejaVu Sans;
    font-size:12px;
    color:#333;
}

h2,h4{
    margin:0;
    padding:0;
}

.header{
    text-align:center;
    margin-bottom:20px;
}

.meta{
    margin-bottom:15px;
}

table{
    width:100%;
    border-collapse:collapse;
}

table th,
table td{
    border:1px solid #ccc;
    padding:8px;
    text-align:center;
}

table th{
    background:#f2f2f2;
}

.text-left{
    text-align:left;
}

.footer{
    margin-top:20px;
    font-size:11px;
    text-align:right;
}

</style>

<div class="header">

    <h2>' .
    htmlspecialchars(
        $school['school_name'] ?? 'School'
    ) .
    '</h2>

    <h4>
        Attendance Report
    </h4>

</div>

<div class="meta">

    <strong>Class:</strong>
    ' . htmlspecialchars($class['class_name']) . '

    <br>

    <strong>Month:</strong>
    ' . htmlspecialchars(
        date(
            'F Y',
            strtotime($start_date)
        )
    ) . '

    <br>

    <strong>Working Days:</strong>
    ' . $working_days . '

</div>

<table>

    <thead>

        <tr>

            <th>Roll</th>
            <th class="text-left">Student Name</th>
            <th>Section</th>
            <th>Present</th>
            <th>Late</th>
            <th>Leave</th>
            <th>Absent</th>
            <th>Attendance %</th>

        </tr>

    </thead>

    <tbody>
';

// ======================================================
// ROWS
// ======================================================

foreach ($students as $student) {

    $summary_stmt = $pdo->prepare("
        SELECT

            SUM(
                CASE
                    WHEN status = 'Present'
                    THEN 1
                    ELSE 0
                END
            ) AS present_days,

            SUM(
                CASE
                    WHEN status = 'Late'
                    THEN 1
                    ELSE 0
                END
            ) AS late_days,

            SUM(
                CASE
                    WHEN status = 'Leave'
                    THEN 1
                    ELSE 0
                END
            ) AS leave_days,

            SUM(
                CASE
                    WHEN status = 'Absent'
                    THEN 1
                    ELSE 0
                END
            ) AS absent_days

        FROM attendance

        WHERE school_id = ?
        AND session_id = ?
        AND student_session_id = ?
        AND attendance_date
        BETWEEN ? AND ?
    ");

    $summary_stmt->execute([

        $school_id,
        $current_session_id,
        $student['student_session_id'],
        $start_date,
        $end_date

    ]);

    $summary = $summary_stmt->fetch(PDO::FETCH_ASSOC);

    $present_days =
        (int) ($summary['present_days'] ?? 0);

    $late_days =
        (int) ($summary['late_days'] ?? 0);

    $leave_days =
        (int) ($summary['leave_days'] ?? 0);

    $absent_days =
        (int) ($summary['absent_days'] ?? 0);

    $attendance_total =
        $present_days +
        $late_days +
        $leave_days;

    $attendance_percentage =
        $working_days > 0

            ? round(
                ($attendance_total / $working_days) * 100,
                2
            )

            : 0;

    $html .= '

        <tr>

            <td>
                ' . htmlspecialchars($student['roll_no']) . '
            </td>

            <td class="text-left">
                ' . htmlspecialchars($student['name']) . '
            </td>

            <td>
                ' . htmlspecialchars($student['section']) . '
            </td>

            <td>
                ' . $present_days . '
            </td>

            <td>
                ' . $late_days . '
            </td>

            <td>
                ' . $leave_days . '
            </td>

            <td>
                ' . $absent_days . '
            </td>

            <td>
                ' . $attendance_percentage . '%
            </td>

        </tr>
    ';
}

$html .= '

    </tbody>

</table>

<div class="footer">

    Generated on :
    ' . date('d M Y h:i A') . '

</div>
';

// ======================================================
// PDF
// ======================================================

$options = new Options();

$options->set('isRemoteEnabled', true);

$dompdf = new Dompdf($options);

$dompdf->loadHtml($html);

$dompdf->setPaper('A4', 'landscape');

$dompdf->render();

$dompdf->stream(

    'attendance_report_' . $month . '.pdf',

    [
        'Attachment' => true
    ]
);

exit;
?>