<?php 
session_name('mini_admin_session');
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'];


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require_once 'vendor/autoload.php';

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

// ----------------------
// Handle notification trigger
// ----------------------
$notification_sent = false;
if (isset($_POST['notify_unmarked_teachers'])) {
    $query = "
        SELECT 
            u.email, 
            u.name, 
            u.lastname, 
            cs.class, 
            cs.section,
            COUNT(DISTINCT s.id) AS total_students,
            COUNT(DISTINCT a.student_id) AS marked_students
        FROM teacher_assignments ta
        JOIN tblusers u ON ta.teacher_id = u.id
        JOIN class_section cs ON ta.class_id = cs.id
        JOIN students s ON s.class = cs.class AND s.section = cs.section AND s.status < 3
        LEFT JOIN attendance a 
            ON a.student_id = s.id 
            AND a.date = CURDATE()
        WHERE ta.is_class_teacher = 1
          AND u.status = 2 
          AND u.permission = 'Teacher'
        GROUP BY u.id, cs.class, cs.section
        HAVING marked_students < total_students
    ";

    $result = mysqli_query($con, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $teacherName = $row['lastname'] . ' ' . $row['name'];
        $email = $row['email'];
        $class = $row['class'];
        $section = $row['section'];

        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = $_ENV['SMTP_HOST'];
            $mail->SMTPAuth = true;
            $mail->Username = $_ENV['SMTP_NO_REPLY'];
            $mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = $_ENV['SMTP_PORT'];
            $mail->Timeout = 10;

            $mail->setFrom($_ENV['SMTP_NO_REPLY'], $_ENV['SCHOOL_NAME']);
            $mail->addAddress($email, $teacherName);

            $mail->isHTML(true);
            $mail->Subject = 'Reminder: Attendance Not Fully Marked';
            $mail->Body = "
            <html><body>
            Dear <strong>$teacherName</strong>,<br><br>
            This is a gentle reminder that you have <b style='color:red;'>not fully marked attendance</b> for 
            <strong>$class - $section</strong> today (" . date('d-m-Y') . ").<br><br>
            Please complete the attendance marking as soon as possible.<br><br>
            Regards,<br>School Admin
            </body></html>";
            $mail->send();
        } catch (Exception $e) {
            error_log("Email failed for $email: {$mail->ErrorInfo}");
        }
    }
    $notification_sent = true;
}

// ----------------------
// Fetch marked and unmarked classes (today)
// ----------------------
$marked = mysqli_query($con, "
    SELECT DISTINCT class, section
    FROM attendance
    WHERE date = CURDATE()
    ORDER BY class, section
");
$unmarked = mysqli_query($con, "
    SELECT class, section
    FROM class_section
    WHERE CONCAT(class, section) NOT IN (
        SELECT CONCAT(class, section) FROM attendance WHERE date = CURDATE()
    )
    ORDER BY class, section
");

// ----------------------
// Weekly attendance tracking (Monâ€“Fri only)
// We'll count distinct a.date per class-section / teacher for the current week (Mon -> today).
// ----------------------
$weekly_attendance = mysqli_query($con, "
    SELECT 
        u.id AS teacher_id,
        CONCAT(u.lastname, ' ', u.name) AS teacher_name,
        cs.class,
        cs.section,
        COUNT(DISTINCT a.date) AS marked_days
    FROM teacher_assignments ta
    JOIN tblusers u ON ta.teacher_id = u.id
    JOIN class_section cs ON ta.class_id = cs.id
    LEFT JOIN attendance a 
        ON cs.class = a.class 
        AND cs.section = a.section 
        AND a.date BETWEEN DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) AND CURDATE()
        AND DAYOFWEEK(a.date) BETWEEN 2 AND 6  -- only Mon-Fri
    WHERE ta.is_class_teacher = 1
      AND u.status = 2
      AND u.permission = 'Teacher'
    GROUP BY u.id, cs.class, cs.section
    ORDER BY marked_days DESC
");

// ----------------------
// Teacher Daily Marking Status (today)
// ----------------------
$teacher_attendance_status = mysqli_query($con, "
    SELECT 
        ta.teacher_id,
        CONCAT(u.lastname, ' ', u.name) AS teacher_name,
        cs.class,
        cs.section,
        COUNT(DISTINCT CASE WHEN a.status = 'Present' THEN a.student_id END) AS present_count,
        COUNT(DISTINCT CASE WHEN a.status = 'Absent' THEN a.student_id END) AS absent_count,
        COUNT(DISTINCT s.id) AS total_students,
        (COUNT(DISTINCT s.id) - COUNT(DISTINCT a.student_id)) AS not_marked
    FROM teacher_assignments ta
    JOIN tblusers u ON ta.teacher_id = u.id
    JOIN class_section cs ON ta.class_id = cs.id
    JOIN students s ON s.class = cs.class AND s.section = cs.section AND s.status < 3
    LEFT JOIN attendance a 
        ON a.student_id = s.id 
        AND a.date = CURDATE()
    WHERE ta.is_class_teacher = 1
      AND u.status = 2
      AND u.permission = 'Teacher'
    GROUP BY ta.teacher_id, cs.class, cs.section
    ORDER BY cs.class, cs.section
");

// ----------------------
// Prepare chart data (labels, data, colors) and also compute expected school days (Mon-Fri) for this week up to today
// ----------------------
$chart_labels = [];
$chart_data = [];
$chart_colors = [];

// Compute week start (Monday) and expected school days (Mon-Fri between week start and today)
$week_start = new DateTime();
$week_start->setTimestamp(strtotime('today -' . (int)date('N', strtotime('today')) + 1 . ' days')); 
// Above line replaced because PHP's date('N') returns 1(Mon)-7(Sun); we'll compute simpler below.

$today = new DateTime('today');
// Determine monday of this week:
$weekday = (int)$today->format('N'); // 1 (Mon) - 7 (Sun)
$days_back = $weekday - 1; // how many days back to monday
$week_start = (clone $today)->modify("-{$days_back} days");

// Count expected school days Mon-Fri from week_start to today
$expected_school_days = 0;
$period = new DatePeriod($week_start, new DateInterval('P1D'), (clone $today)->modify('+1 day'));
foreach ($period as $d) {
    $dow = (int)$d->format('N');
    if ($dow >= 1 && $dow <= 5) $expected_school_days++;
}

// Build chart arrays
mysqli_data_seek($weekly_attendance, 0);
while ($row = mysqli_fetch_assoc($weekly_attendance)) {
    $name = $row['teacher_name'] . " (" . $row['class'] . $row['section'] . ")";
    $days = (int)$row['marked_days']; // days teacher marked this week (Mon-Fri)
    $chart_labels[] = $name;
    $chart_data[] = $days;

    // Color logic relative to expected_school_days
    // if expected_school_days is zero (shouldn't happen), fallback to 5 for color logic
    $maxDaysForColor = $expected_school_days > 0 ? $expected_school_days : 5;
    $pct = $days / $maxDaysForColor;

    if ($pct <= 0.4) {
        $chart_colors[] = '#dc3545'; // poor
    } elseif ($pct <= 0.79) {
        $chart_colors[] = '#ffc107'; // average
    } else {
        $chart_colors[] = '#28a745'; // good
    }
}

$chart_labels_json = json_encode($chart_labels);
$chart_data_json = json_encode($chart_data);
$chart_colors_json = json_encode($chart_colors);
$expected_school_days_js = (int)$expected_school_days;
?>

<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
<?php @include("includes/header2.php"); ?>
<?php @include("includes/sidebar2.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-users"></i>
                        </div>
                        <div>
                            <h1 class="premium-title text-primary">
                                Attendance Management
                                <span class="premium-subtitle text-secondary">Monitor Attendance</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="dashboard1.php" class="text-primary">Home</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Attendance Monitoring</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</section> 

    <!-- âœ… Existing Attendance Status -->
    <section class="content">
        <div class="card card-primary card-outline">
            <div class="card-header bg-primary text-white d-flex justify-content-between">
                <h5 class="m-0">
                    <i class="fas fa-calendar-day"></i> 
                    Attendance Status for Today (<?= date('Y-m-d'); ?>)
                </h5>
                <form method="POST" class="m-0">
                    <button type="submit" name="notify_unmarked_teachers" class="btn btn-warning btn-sm">
                        <i class="fas fa-bell"></i> Notify Unmarked Teachers
                    </button>
                </form>
            </div> <!-- /.card-header -->

            <div class="card-body">
                <?php if ($notification_sent): ?>
                    <div class="alert alert-success">
                        Notification sent to all unmarked class teachers.
                    </div>
                <?php endif; ?>
            
<form action="download_class_attendance.php" method="GET">
    <div class="row">
        <!-- Select Class -->
        <div class="form-group col-md-3">
            <label for="class_id">Select Class:</label>
            <select name="class_id" id="class_id" class="form-control" required>
                <option value="">-- Select Class --</option>
                <?php
                $classes = mysqli_query($con, "SELECT id, class, section FROM class_section ORDER BY class, section");
                while ($c = mysqli_fetch_assoc($classes)) {
                    echo '<option value="'.$c['id'].'">'.$c['class'].' '.$c['section'].'</option>';
                }
                ?>
            </select>
        </div>

        <!-- Start Date -->
        <div class="form-group col-md-3">
            <label for="start_date">Start Date:</label>
            <input type="date" name="start_date" id="start_date" class="form-control" required>
        </div>

        <!-- End Date -->
        <div class="form-group col-md-3">
            <label for="end_date">End Date:</label>
            <input type="date" name="end_date" id="end_date" class="form-control" required>
        </div>

        <!-- File Type -->
        <div class="form-group col-md-3">
            <label for="format">File Type:</label>
            <select name="format" id="format" class="form-control">
                <option value="xlsx">Excel (.xlsx)</option>
                <option value="csv">CSV (.csv)</option>
            </select>
        </div>

        <!-- Submit Button -->
        <div class="form-group col-md-12 text-center mt-2">
            <button type="submit" class="btn btn-success">
                <i class="fas fa-download"></i> Download Attendance
            </button>
        </div>
    </div>
</form>


                <?php if (mysqli_num_rows($teacher_attendance_status) > 0): ?>
                    <table class="table table-bordered table-hover" id="example1">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Teacher</th>
                                <th>Class</th>
                                <th>Arm</th>
                                <th>Present</th>
                                <th>Absent</th>
                                <th>Not Marked</th>
                                <th>Total Students</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php 
                        $sn = 1; 
                        while ($row = mysqli_fetch_assoc($teacher_attendance_status)): 
                            $fully_marked = ($row['present_count'] + $row['absent_count']) == $row['total_students'];
                            $notify_flag = !$fully_marked; // âœ… Flag teachers that will be notified
                        ?>
                        <tr <?php if ($notify_flag) echo 'style="background-color: #fff3cd;"'; ?>>
                            <td><?= $sn++; ?></td>
                            <td><?= $row['teacher_name']; ?></td>
                            <td><?= $row['class']; ?></td>
                            <td><?= $row['section']; ?></td>
                            <td><?= $row['present_count']; ?></td>
                            <td><?= $row['absent_count']; ?></td>
                            <td><?= $row['not_marked']; ?></td>
                            <td><?= $row['total_students']; ?></td>
                            <td>
                                <?php if ($fully_marked): ?>
                                    <span class="badge badge-success">Completed</span>
                                <?php else: ?>
                                    <span class="badge badge-warning">Incomplete</span>
                                    <small class="text-danger d-block">Will be notified</small>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p>No attendance data for today.</p>
                <?php endif; ?>
            </div> <!-- /.card-body -->
        </div> <!-- /.card -->
    </section>
    <!-- /âœ… NEW: Teacher Daily Marking Status -->

    <!-- Weekly Attendance Report -->
         <section class="content">
        <div class="card card-primary card-outline">
            <div class="card-header bg-primary text-white">
                <h5 class="m-0"><i class="fas fa-file-excel"></i> Weekly Attendance Report Sheet (Monâ€“Fri)</h5>
                <small class="text-white-50 ml-3">School days counted this week: <strong><?= $expected_school_days ?></strong></small>
            </div>            
            <div class="card-body">
                     <form action="download_teacher_attendance.php" method="GET">
        <div class="row">
        <!-- Start Date -->
        <div class="form-group col-md-6">
            <label for="start_date">Start Date:</label>
            <input type="date" name="start_date" id="start_date" class="form-control" required>
        </div>

        <!-- End Date -->
        <div class="form-group col-md-6">
            <label for="end_date">End Date:</label>
            <input type="date" name="end_date" id="end_date" class="form-control" required>
        </div>

        <!-- Submit Button -->
        <div class="form-group col-md-12 text-center mt-2">
            <button type="submit" class="btn btn-success">
                <i class="fas fa-file-download"></i> Download Excel Report Sheet
            </button>
        </div>
        </div>
        </form>
                </div>
            </div>

         

    </section><!-- /Weekly Attendance Report -->

    <!-- Weekly Performance Chart (Mon-Fri only) -->
    <section class="content">
        <div class="card card-success card-outline">
            <div class="card-header bg-success text-white">
                <h5 class="m-0"><i class="fas fa-chart-bar"></i> Weekly Attendance Performance (Monâ€“Fri)</h5>
                <small class="text-white-50 ml-3">School days counted this week: <strong><?= $expected_school_days ?></strong></small>
            </div>
            <div class="card-body">
                <canvas id="weeklyAttendanceChart" height="100"></canvas>
            </div>
        </div>
    </section>

</div>

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

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('weeklyAttendanceChart').getContext('2d');

const labels = <?= $chart_labels_json; ?>;
const data = <?= $chart_data_json; ?>;
const colors = <?= $chart_colors_json; ?>;
const expectedDays = <?= $expected_school_days_js; ?> || 5; // fallback to 5

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: [{
            label: 'Days Marked Attendance (Monâ€“Fri)',
            data: data,
            backgroundColor: colors,
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            tooltip: {
                callbacks: {
                    label: function(context) {
                        const daysMarked = context.parsed.y;
                        const pct = expectedDays > 0 ? (daysMarked / expectedDays) : 0;
                        // Convert to rating out of 5
                        const rating = Math.round((pct * 5) * 10) / 10; // 1 decimal
                        return `${daysMarked} days (Rating: ${rating}/5)`;
                    }
                }
            },
            legend: { display: false }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    stepSize: 1
                },
                suggestedMax: Math.max(expectedDays, 5) // ensures chart scale fits expected school days
            }
        }
    }
});
    $(document).ready(function() {
      $('#class_id,#format').select2();

    });
</script>
</body>
</html>
