<?php
session_start();
if(isset($_SESSION['username'])){
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include 'includes/styles.php'; ?>
        <title>Attendance Dashboard | <?php echo $school_name; ?></title>

        <?php
        require_once 'Classes/Attendance.php';
        $attendance = new Attendance();

        function time_elapsed_string($datetime)
       {
            $now = new DateTime;
            $ago = new DateTime($datetime);
            $diff = $now->diff($ago);

            if ($diff->d > 0) return $diff->d . ' day' . ($diff->d > 1 ? 's' : '') . ' ago';
if ($diff->h > 0) return $diff->h . ' hour' . ($diff->h > 1 ? 's' : '') . ' ago';
            if ($diff->i > 0) return $diff->i . ' minute' . ($diff->i > 1 ?'s' : '') . ' ago';
            return 'Just now';
        }
        ?>
        <style>
            .info-box {
                min-height: 120px;
                background: #fff;
                border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                margin-bottom: 20px;
                display: flex;
                align-items: center;
                padding: 15px;
            }
            .info-box-icon {
                width: 80px;
                height: 80px;
               border-radius: 8px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 2.5rem;
                color: white;
            }
            .info-box-content {
                flex: 1;
                padding-left: 20px;
            }
           .info-box-text {
                font-size: 0.9rem;
                color: #666;
                margin-bottom: 5px;
            }
            .info-box-number {
                font-size: 2rem;
                font-weight: bold;
                margin-bottom: 5px;
            }
            .info-box-percentage {
                font-size: 0.85rem;
                color: #999;
            }
.bg-present { background: linear-gradient(135deg, #28a745, #20c997); }
            .bg-absent { background: linear-gradient(135deg, #dc3545, #e83e8c); }
           .bg-late { background: linear-gradient(135deg, #ffc107, #fd7e14); }
            .bg-total { background: linear-gradient(135deg, #007bff, #6610f2); }

            .alert-card {
               border-left: 4px solid;
                padding: 15px;
                margin-bottom: 10px;
                border-radius: 4px;
                background: #fff;
}
            .alert-critical { border-color: #dc3545; background: #fff5f5; }
                    .alert-warning { border-color: #ffc107; background: #fffbf0; }

            .class-card {
                background: white;
                border-radius: 8px;
                padding: 15px;
                margin-bottom: 15px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                transition: transform 0.2s;
            }
            .class-card:hover {
                transform:translateY(-2px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            }
            .class-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 10px;
           }
            .class-name {
                font-size: 1.1rem;
                font-weight: bold;
                color: #333;
            }
            .class-percentage {
                font-size: 1.5rem;
                font-weight: bold;
            }
            .percentage-good { color: #28a745; }
            .percentage-medium { color: #ffc107; }
            .percentage-low {color: #dc3545; }

            .progress-container {
                height: 8px;
                background: #e9ecef;
                border-radius: 4px;
                overflow: hidden;
                margin-bottom: 10px;
            }
            .progress-bar-custom {
                height: 100%;
                transition: width 0.3s;
            }

            .quick-action-btn {
                width: 100%;
                padding: 15px;
               margin-bottom: 10px;
                border-radius: 8px;
                border: none;
                color: white;
               font-size: 1rem;
                cursor: pointer;
                transition: transform 0.2s;
            }
            .quick-action-btn:hover {
                transform: scale(1.02);
            }
            .btn-mark { background: linear-gradient(135deg, #007bff, #0056b3); }
            .btn-view { background: linear-gradient(135deg, #28a745, #1e7e34); }
            .btn-report { background: linear-gradient(135deg, #17a2b8, #117a8b); }

            .recent-activity {
                max-height: 400px;
                overflow-y: auto;
            }
            .activity-item {
                padding: 10px;
                border-bottom: 1px solid #eee;
            }
            .activity-time {
                font-size:0.8rem;
                color: #999;
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
   <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0">Attendance Dashboard</h1>
                        </div>
                        <div class="col-sm-6">
                           <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                                <li class="breadcrumb-item active">Attendance Dashboard</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>


            <section class="content">
                <div class="container-fluid">

                    <!-- Today's Summary -->
                    <div class="row">
                        <div class="col-md-12">
                            <h4><i class="fas fa-calendar-day"></i> Today's Attendance - <?php echo date('F d, Y'); ?></h4>
                        </div>
                    </div>

                    <div class="row">
                        <?php
                        $today = date('Y-m-d');

                        // Get today's total students
                        $sql = "SELECT COUNT(*) as total FROM student";
                        $conn->query($sql);
                        $totalStudents = $conn->fetchColumn();

                        // Get today's present count
                        $sql = "SELECT COUNT(*) as count FROM student_attendance 
                            WHERE attendance_date = :today AND status = 'Present'";
                        $conn->query($sql);
                        $conn->bind(':today', $today);
                        $presentCount = $conn->fetchColumn();

                        // Get today's absent count
                        $sql ="SELECT COUNT(*) as count FROM student_attendance 
                            WHERE attendance_date = :today AND status = 'Absent'";
                        $conn->query($sql);
                        $conn->bind(':today', $today);
                        $absentCount = $conn->fetchColumn();

                        // Get today's late count
                        $sql = "SELECT COUNT(*) as count FROM student_attendance 
                            WHERE attendance_date = :today AND status = 'Late'";
                        $conn->query($sql);
                        $conn->bind(':today', $today);
                        $lateCount = $conn->fetchColumn();

                        $markedCount = $presentCount +$absentCount + $lateCount;
                        $notMarkedCount = $totalStudents - $markedCount;
                        $presentPercentage = $totalStudents > 0 ? round(($presentCount / $totalStudents) * 100, 1) : 0;
                        ?>

                        <div class="col-lg-3 col-md-6">
                            <div class="info-box">
                                <div class="info-box-icon bg-total">
                                    <i class="fas fa-users"></i>
                                </div>
                                <div class="info-box-content">
                                    <div class="info-box-text">Total Students</div>
                                    <div class="info-box-number"><?php echo $totalStudents; ?></div>
                                    <div class="info-box-percentage">
                                        <?php echo $markedCount; ?>marked today
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-md-6">
                            <div class="info-box">
                                <div class="info-box-icon bg-present">
                                    <i class="fas fa-check-circle"></i>
                               </div>
                                <div class="info-box-content">
                                    <div class="info-box-text">Present Today</div>
                                   <div class="info-box-number"><?php echo $presentCount; ?></div>
                                    <div class="info-box-percentage">
                                        <?php echo $presentPercentage; ?>% attendance</div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-md-6">
                            <div class="info-box">
                                <div class="info-box-icon bg-absent">
                                    <i class="fas fa-times-circle"></i>
                                </div>
                                <div class="info-box-content">
                                    <div class="info-box-text">Absent Today</div>
                                    <div class="info-box-number"><?php echo $absentCount; ?></div>
                                    <div class="info-box-percentage">
                                        <?php echo $totalStudents > 0 ?round(($absentCount / $totalStudents) * 100, 1) : 0; ?>% of total
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-md-6">
                            <div class="info-box">
                                <div class="info-box-icon bg-late">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <div class="info-box-content">
                                    <div class="info-box-text">Late Today</div>
                                    <div class="info-box-number"><?php echo $lateCount; ?></div>
                                    <div class="info-box-percentage">
                                        <?php echo $notMarkedCount; ?> not marked yet
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alerts & Quick Actions Row -->
                    <div class="row">
                        <!-- Attendance Alerts -->
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header bg-warning">
                                    <h3 class="card-title"><i class="fas fa-exclamation-triangle"></i> Attendance Alerts</h3>
                                </div>
                                <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                                    <?php
                                    // Get students with low attendance
                                    $sql = "SELECT s.name, s.registerNO, c.name as class_name, 
                                        astt.attendance_percentage
                                        FROM student s
                                        LEFT JOIN classes c ON s.classesID = c.id
                                        LEFT JOIN attendance_statistics astt ON s.studentID = astt.student_id
                                        WHERE astt.attendance_percentage < 75
                                        ORDER BY astt.attendance_percentage ASC
                                        LIMIT 10";
                                    $conn->query($sql);
                                    $lowAttendance = $conn->fetchMultiple();

                                    if($conn->rowCount() > 0) {
                                        foreach($lowAttendance as $student) {
                                            $alertClass = $student->attendance_percentage < 60 ? 'alert-critical' : 'alert-warning';
                                            echo '<div class="alert-card '.$alertClass.'">
                                                <strong>'.$student->name.'</strong> ('.$student->registerNO.') - '.$student->class_name.'
                                                <br><small>Attendance: '.$student->attendance_percentage.'%</small>
                                              </div>';
                                        }
                                    } else {
                                        echo '<p class="text-center text-muted">No attendance alerts</p>';
                                  }

                                    // Get students absent for consecutive days
                                    $sql = "SELECT s.name, s.registerNO, c.name as class_name,
                                        COUNT(*) as consecutive_days
                                        FROM student_attendance sa
                                        JOIN student s ON sa.student_id = s.studentID
                                        JOIN classes c ON s.classesID =c.id
                                        WHERE sa.status = 'Absent' 
                                        AND sa.attendance_date >= DATE_SUB(CURDATE(), INTERVAL 5 DAY)
                                        GROUP BY sa.student_id, s.name, s.registerNO, c.name
                                        HAVING COUNT(*) >= 3
                                        ORDER BY consecutive_days DESC";
                                    $conn->query($sql);
                                    $consecutive = $conn->fetchMultiple();

                                    if($conn->rowCount() > 0) {
                                        foreach($consecutive as $student) {
                                            echo '<div class="alert-card alert-critical">
                                                <i class="fas fa-bell"></i> 
                                              <strong>'.$student->name.'</strong> ('.$student->registerNO.')
                                                <br><small>Absent for '.$student->consecutive_days.' consecutive days</small>
                                              </div>';
                                        }
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>

                        <!-- Quick Actions -->
                       <div class="col-md-6">
                            <div class="card">
                                <div class="card-header bg-primary">
                                    <h3 class="card-title"><i class="fas fa-bolt"></i> Quick Actions</h3>
                                </div>
                                <div class="card-body">
                                    <button class="quick-action-btn btn-mark" onclick="location.href='mark-attendance.php'">
                                        <i class="fas fa-check-double"></i> Mark Attendance
                                    </button>
                                    <button class="quick-action-btn btn-view" onclick="location.href='attendance-report.php'">
                                        <i class="fas fa-chart-bar"></i> View Reports
                                    </button>
                                    <button class="quick-action-btn btn-report" onclick="location.href='student-attendance-history.php'">
                                        <i class="fas fa-history"></i> Student History
                                    </button>

                                    <div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                                        <h5>Today's Progress</h5>
                                        <div class="progress-container">
                                            <div class="progress-bar-custom bg-success"
                                                 style="width: <?php echo$totalStudents > 0 ? ($markedCount / $totalStudents) * 100 : 0; ?>%">
                                            </div>
                                        </div>
                                        <small><?php echo $markedCount; ?> of <?php echo $totalStudents; ?> students marked</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Class-wise Attendance -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header bg-success">
                                    <h3 class="card-title"><i class="fas fa-school"></i> Class-wise Attendance Today</h3>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php
                                        $sql = "SELECT c.id, c.name as class_name,
                                            COUNT(DISTINCT s.studentID) as total_students,
                                            COUNT(DISTINCT CASE WHEN sa.status = 'Present' THEN sa.student_id END) as present_count,
                                           COUNT(DISTINCT CASE WHEN sa.status = 'Absent' THEN sa.student_id END) as absent_count,
                                            COUNT(DISTINCT CASE WHEN sa.attendance_date = :today THEN sa.student_id END) as marked_count
                                            FROM classes c
                                            LEFT JOIN student s ON c.id = s.classesID
                                           LEFT JOIN student_attendance sa ON s.studentID = sa.student_id AND sa.attendance_date = :today
                                            GROUP BY c.id, c.name
                                            ORDER BY c.name";
                                       $conn->query($sql);
                                        $conn->bind(':today', $today);
                                        $classes = $conn->fetchMultiple();

                                        if($conn->rowCount() > 0) {
                                            foreach($classes as $class) {
                                                $percentage = $class->total_students > 0
                                                    ? round(($class->present_count / $class->total_students) * 100, 1)
                                                    : 0;
                                                        $percentageClass = $percentage >= 80 ? 'percentage-good'
                                                    : ($percentage >= 60 ? 'percentage-medium' : 'percentage-low');

                                                echo '<div class="col-md-4">
                                                    <div class="class-card">
                                                        <div class="class-header">
                                                            <div class="class-name">'.$class->class_name.'</div>
                                                            <div class="class-percentage '.$percentageClass.'">'.$percentage.'%</div>
                                                        </div>
                                                        <div class="progress-container">
                                                            <div class="progress-bar-custom bg-success" style="width: '.$percentage.'%"></div>
                                                        </div>
                                                        <div style="font-size: 0.9rem; color: #666;">
                                                            <i class="fas fa-check text-success"></i> '.$class->present_count.' Present &nbsp;
                                                            <i class="fas fa-times text-danger"></i> '.$class->absent_count.' Absent<br>
                                                            <small>'.$class->marked_count.' of '.$class->total_students.' marked</small>
                                                        </div>
                                                    </div>
                                                  </div>';
                                            }
                                        } else {
                                            echo '<div class="col-12"><p class="text-center text-muted">No classes found</p></div>';
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Activity -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header bg-info">
                                    <h3 class="card-title"><i class="fas fa-history"></i> Recent Attendance Activity</h3>
                                </div>
                                <div class="card-body recent-activity">
                                    <?php
                                    $sql = "SELECT bal.*, c.name as class_name, sec.name as section_name,bal.total_students
                                        FROM bulk_attendance_logs bal
                                        LEFT JOIN classes c ON bal.class_id = c.id
                                        LEFT JOIN sections sec ON bal.section_id = sec.id
                                        ORDER BY bal.marked_at DESC
                                        LIMIT 20";
                                    $conn->query($sql);
                                    $activities = $conn->fetchMultiple();

                                    if($conn->rowCount() > 0) {
                                        foreach($activities as $activity) {
                                            $timeAgo = time_elapsed_string($activity->marked_at);
                                            echo '<div class="activity-item">
                                                <i class="fas fa-check-circle text-success"></i>
                                            <strong>'.$activity->marked_by.'</strong> marked attendance for 
                                                <strong>'.$activity->class_name.' - '.$activity->section_name.'</strong>
                                                ('.$activity->total_students.' students)
                                                <br><span class="activity-time">'.$timeAgo.'</span>
                                              </div>';
                                        }
                                    } else {
                                        echo '<p class="text-center text-muted">No recent activity</p>';
                                    }
                                    ?>
                                </div>
                            </div>
                    </div>
                    </div>

                </div>
            </section>

        </div>

        <?php include "includes/footer.php"; ?>

    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include 'includes/styles.php'; ?>
    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6>You need to login to continue</h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $link;?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>