<?php error_reporting(0); ?>
<?php    session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php include '../admin/includes/styles.php'; ?>
    <title> Learning Materials | <?php echo $school_name; ?> </title>

    <style>
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 4px6px rgba(0,0,0,0.1);
            text-align: center;
        }
        .stats-icon {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
           justify-content: center;
            font-size: 2rem;
            color: white;
            margin-bottom: 15px;
        }
        .icon-present { background: linear-gradient(135deg, #28a745, #20c997); }
        .icon-absent{ background: linear-gradient(135deg, #dc3545, #e83e8c); }
        .icon-late { background: linear-gradient(135deg, #ffc107, #fd7e14); }
        .icon-percentage { background:linear-gradient(135deg, #007bff, #6610f2); }

        .stats-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin: 10px 0;
        }
        .stats-label {
            color:#666;
            font-size: 0.95rem;
        }

        .attendance-calendar {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
       }
        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 8px;
}
        .calendar-day {
            aspect-ratio: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size:0.9rem;
            transition: all 0.3s;
        }
        .calendar-day:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        .day-header{
            font-weight: bold;
            color: #666;
            border: none;
        }
        .day-present { background: #28a745; color: white; border-color: #28a745; }
        .day-absent { background: #dc3545; color: white; border-color: #dc3545; }
        .day-late { background: #ffc107; color: #000; border-color: #ffc107; }
        .day-excused { background: #17a2b8;color: white; border-color: #17a2b8; }
        .day-weekend { background: #f5f5f5; color: #999; }
        .day-future { background: #fafafa; color: #ccc; cursor: not-allowed; }

      .legend {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
      .legend-box {
            width: 20px;
            height: 20px;
            border-radius: 4px;
        }

        .history-table {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
          margin-top: 20px;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        .badge-present { background: #28a745; color: white; }
        .badge-absent { background: #dc3545; color: white; }
        .badge-late { background: #ffc107; color: #000; }
        .badge-excused { background: #17a2b8; color: white; }

        .request-leave-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background:linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            border: none;
            font-size: 1.5rem;
            box-shadow: 0 4px 12px rgba(0,123,255,0.4);
            cursor: pointer;
            transition: all 0.3s;
            z-index: 1000;
        }
        .request-leave-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 16px rgba(0,123,255,0.6);
        }

        .profile-section {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
           display: flex;
            align-items: center;
            gap: 20px;
        }
        .profile-photo {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            border: 4px solid #007bff;
        }
        .profile-info h3 {
            margin: 0 0 10px 0;
            color: #333;
        }
        .profile-info p {
            margin: 5px 0;
            color: #666;
        }

        .history-table {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-top: 20px;
        }
    </style>



   <?php
    session_start();
    if(isset($_SESSION['student'])){

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

    // Get student ID
    $sql = "SELECT *  FROM student WHERE username = :username";
    $conn->query($sql);
   $conn->bind(':username', $_SESSION['student']);
    $studentData = $conn->fetchSingle();

    if (!$studentData) {
        header("Location: $student_login_link");
        exit();
    }

    $studentId = $studentData->studentID;

    ?>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php include "includes/sidebar.php";?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
<!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0"> My Attendance </h1>
                    </div><!--/.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->student_url(); ?>">Home</a></li>
                            <li class="breadcrumb-item active">My Attendance </li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->

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

                <!-- Profile Section -->
                <div class="profile-section">
                    <?php
                    $photoUrl = !empty($studentData->photo) ? '../admin/upload/' . $studentData->photo : '../admin/upload/default.png';

                    // Get class and section names
                    $sql = "SELECT c.name as class_name, s.name as section_name 
                            FROM classes c, sections s 
                            WHERE c.id = :class_id AND s.id = :section_id";
                    $conn->query($sql);
                    $conn->bind(':class_id', $studentData->classesID);
                    $conn->bind(':section_id', $studentData->sectionid);
                    $classInfo= $conn->fetchSingle();

                    ?>
                    <img src="<?php echo $photoUrl; ?>" alt="Profile Photo" class="profile-photo">
                    <div class="profile-info">
                        <h3><?php echo $studentData->name; ?></h3>
                        <p><i class="fasfa-id-card"></i> <strong>Reg No:</strong> <?php echo $studentData->registerNO; ?></p>
                        <p><i class="fas fa-school"></i> <strong>Class:</strong> <?php echo $classInfo->class_name; ?> - <?php echo $classInfo->section_name; ?></p>
                    </div>
                </div>

                <!-- Statistics Cards -->
                <?php
                $stats = $attendance->getStudentStatistics($studentId);
                $totalDays = $stats ? $stats->total_days : 0;
                $presentDays = $stats ? $stats->present_days : 0;
                $absentDays = $stats ? $stats->absent_days : 0;
                $lateDays = $stats ? $stats->late_days : 0;
                $attendancePercentage = $stats ? $stats->attendance_percentage : 0;
                ?>

                <div class="row">
                    <div class="col-lg-3 col-md-6">
                        <div class="stats-card">
                            <div class="stats-icon icon-percentage">
                                <i class="fas fa-percent"></i>
                            </div>
                            <div class="stats-number" style="color: <?php echo $attendancePercentage >= 75 ? '#28a745' : ($attendancePercentage >= 60 ? '#ffc107' : '#dc3545'); ?>">
                                <?php echo $attendancePercentage; ?>%
                            </div>
                            <div class="stats-label">OverallAttendance</div>
                            <small class="text-muted"><?php echo $totalDays; ?> total days</small>
                        </div>
                    </div>

                    <div class="col-lg-3 col-md-6">
                        <div class="stats-card">
                            <div class="stats-icon icon-present">
                               <i class="fas fa-check-circle"></i>
                            </div>
                            <div class="stats-number" style="color: #28a745;">
                                <?php echo $presentDays; ?>
                            </div>
                            <div class="stats-label">Present Days</div>
                            <small class="text-muted"><?php echo $totalDays > 0 ? round(($presentDays/$totalDays)*100, 1) : 0; ?>% of total</small>
                        </div>
                    </div>

                    <div class="col-lg-3 col-md-6">
                        <div class="stats-card">
                            <div class="stats-icon icon-absent">
                                <i class="fas fa-times-circle"></i>
                            </div>
                            <div class="stats-number" style="color: #dc3545;">
                                <?php echo $absentDays; ?>
                            </div>
                            <div class="stats-label">Absent Days</div>
                          <small class="text-muted"><?php echo $totalDays > 0 ? round(($absentDays/$totalDays)*100, 1) : 0; ?>% of total</small>
                        </div>
                    </div>

                    <div class="col-lg-3 col-md-6">
                    <div class="stats-card">
                            <div class="stats-icon icon-late">
                                <i class="fas fa-clock"></i>
                            </div>
                            <div class="stats-number" style="color: #ffc107;">
                                <?php echo $lateDays; ?>
                            </div>
                            <div class="stats-label">Late Days</div>
                            <small class="text-muted"><?php echo $totalDays > 0 ? round(($lateDays/$totalDays)*100, 1) : 0; ?>% of total</small>
                        </div>
                    </div>
                </div>

                <!-- Attendance Calendar -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="attendance-calendar">
                            <div class="calendar-header">
                                <button class="btn btn-outline-primary" id="prev-month">
                                    <i class="fas fa-chevron-left"></i> Previous
                                </button>
                                <h4 id="current-month"></h4>
                                <button class="btn btn-outline-primary" id="next-month">
                                    Next <i class="fas fa-chevron-right"></i>
                                </button>
                            </div>

                            <div class="calendar-grid" id="calendar-grid">
                                <!-- Calendar will be populated by JavaScript -->
                            </div>

                            <div class="legend">
                                <div class="legend-item">
                                    <div class="legend-box day-present"></div>
                                    <span>Present</span>
                                </div>
                                <div class="legend-item">
                                    <div class="legend-box day-absent"></div>
                                    <span>Absent</span>
                                </div>
                                <div class="legend-item">
                                    <div class="legend-box day-late"></div>
                                    <span>Late</span>
                                </div>
                                <div class="legend-item">
                                <div class="legend-box day-excused"></div>
                                   <span>Excused</span>
                                </div>
                                <div class="legend-item">
                                    <div class="legend-box day-weekend"></div>
                                    <span>Weekend</span>
                                </div>
                            </div>
                       </div>
                    </div>
                </div>

                <!-- RecentAttendance History -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="history-table">
                            <h4><i class="fas fa-history"></i> Recent Attendance History</h4>
                           <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Day</th>
                                        <th>Status</th>
                                        <th>Time In</th>
                                        <th>Remarks</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                    $history = $attendance->getStudentAttendanceHistory($studentId, 30);
                                    if($history) {
                                        foreach($history as $record) {
                                            $date = new DateTime($record->attendance_date);
                                            $dayName =$date->format('l');
                                            $statusClass = 'badge-' . strtolower($record->status);

                                            echo '<tr>
                                                    <td>'.$date->format('M d, Y').'</td>
                                                    <td>'.$dayName.'</td>
                                                    <td><span class="status-badge '.$statusClass.'">'.$record->status.'</span></td>
                                                    <td>'.($record->time_in ?: '-').'</td>
                                                    <td>'.($record->remarks ?: '-').'</td>
                                                </tr>';
                                        }
                                    } else {
                                        echo '<tr><td colspan="5" class="text-center text-muted">No attendance recordsfound</td></tr>';
                                    }
                                    ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- My Leave Requests Section -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="history-table">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h4><i class="fas fa-calendar-times"></i> My Leave Requests</h4>
                                <a href="<?php echo $conn->student_url().'view-leave-requests'; ?>" class="btn btn-primary btn-sm">
                                   <i class="fas fa-eye"></i> View All
                                </a>
                            </div>

                            <?php
                            // Get recent leave requests
                            $sql = "SELECT * FROM attendance_leave_requests 
                            WHERE student_id = :student_id 
                            ORDER BY requested_at DESC 
                            LIMIT 5";
                            $attendance->query($sql);
                           $attendance->bind(':student_id', $studentId);
                            $leave_requests = $attendance->fetchMultiple();

                            if($attendance->rowCount() > 0) {
                                ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                        <tr>
                                            <th>Leave Type</th>
                                            <th>Start Date</th>
                                            <th>End Date</th>
                                            <th>Days</th>
                                            <th>Status</th>
                                            <th>Submitted</th>
                                        </tr>
                                        </thead>
                                       <tbody>
                                        <?php
                                        foreach($leave_requests as $request) {
                                            $startDate = new DateTime($request->leave_from);
                                            $endDate = new DateTime($request->leave_to);
                                            $days = $startDate->diff($endDate)->days + 1;

                                            $statusClass = 'badge-';
                                            switch($request->status) {
                                            case 'pending':
                                                    $statusClass .= 'warning';
                                                    break;
                                                case 'approved':
                                                    $statusClass .= 'success';
                                                    break;
                                                case 'rejected':
                                                    $statusClass .= 'danger';
                                                    break;
                                            }

                                            echo '<tr>
                                   <td><span class="badge badge-info">'.ucfirst($request->leave_type).'</span></td>
                                    <td>'.$startDate->format('M d, Y').'</td>
                                    <td>'.$endDate->format('M d, Y').'</td>
                                    <td>'.$days.' day'.($days > 1? 's' : '').'</td>
                                    <td><span class="badge '.$statusClass.'">'.ucfirst($request->status).'</span></td>
                                    <td>'.date('M d, Y', strtotime($request->created_at)).'</td>
                                </tr>';
                                        }
                                        ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php
                            } else {
                                echo '<div class="text-center text-muted" style="padding: 40px;">
                                   <i class="fas fa-calendar-times" style="font-size: 3rem; opacity: 0.3;"></i>
                                      <p style="margin-top: 15px;">No leave requests yet. Click the button below to request leave.</p>
                </div>';
                            }
                            ?>
                        </div>
                    </div>
                </div>

            </div>
        </section>

        <!-- /.content -->
    </div>
<!-- /.content-wrapper -->
    <?php include "../admin/includes/footer.php";?>

    <!-- Request Leave Button -->
    <button class="request-leave-btn" data-toggle="modal" data-target="#leaveModal" title="Request Leave">
        <i class="fas fa-plus"></i>
    </button>

   <!-- Leave Request Modal -->
    <div class="modal fade" id="leaveModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fas fa-calendar-times"></i> Request Leave</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form id="leave-request-form">
                    <div class="modal-body">
                        <div class="form-group">
                            <label>LeaveType <span class="text-danger">*</span></label>
                            <select class="form-control" name="leave_type" required>
                                <option value="">Select Type</option>
                                <option value="sick">Sick Leave</option>
                                <option value="family">Family Emergency</option>
                                <option value="personal">Personal</option>
                                <option value="other">Other</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Start Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" name="start_date" id="start_date" required>
                        </div>

                        <div class="form-group">
                            <label>End Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" name="end_date" id="end_date" required>
                        </div>

                        <div class="form-group">
                            <label>Reason <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="reason" rows="4" required placeholder="Please explain your reason for leave..."></textarea>
                        </div>

                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            <small>Your leave request will be reviewed by the administration. You will be notified once it's processed.</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="submit-leave-btn">
                            <i class="fas fa-paper-plane"></i> Submit Request
                        </button>
                    </div>
                </form>
            </div>
</div>
    </div>

    <script>
        let currentMonth = new Date();
        const studentId = <?php echo $studentId; ?>;

        $(document).ready(function() {
            loadCalendar();

            // Set minimum date to today
            const today= new Date().toISOString().split('T')[0];
            $('#start_date, #end_date').attr('min', today);

            // Validate end date is after start date
            $('#start_date').on('change', function() {
                $('#end_date').attr('min', $(this).val());
                if($('#end_date').val() && $('#end_date').val() < $(this).val()) {
                    $('#end_date').val($(this).val());
                }
            });

            // Month navigation
            $('#prev-month').on('click', function() {
                currentMonth.setMonth(currentMonth.getMonth() - 1);
                loadCalendar();
            });

            $('#next-month').on('click', function() {
                currentMonth.setMonth(currentMonth.getMonth() + 1);
                loadCalendar();
            });

            // Leave request form
            $('#leave-request-form').on('submit', function(e) {
                e.preventDefault();
                submitLeaveRequest();
            });
        });

        function loadCalendar() {
            const month = currentMonth.getMonth();
            const year = currentMonth.getFullYear();

            $('#current-month').text(currentMonth.toLocaleDateString('en-US', {month: 'long', year: 'numeric'}));

            $.ajax({
                url: 'api/get-monthly-attendance.php',
                type: 'POST',
                data: {
                    student_id: studentId,
                    month: month + 1,
                    year: year
                },
                dataType: 'json',
                success: function(data) {
                    console.log('Attendance data:', data); // For debugging
                    renderCalendar(data);
                },
                error: function(xhr, status, error) {
                    console.log('Error fetching attendance data:', error); // For debugging
                }
            });
        }

        function renderCalendar(attendanceData) {
            const month = currentMonth.getMonth();
            const year = currentMonth.getFullYear();
            const firstDay = new Date(year, month, 1).getDay();
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            const today = new Date();

            let html = '';

            // Day headers
           ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].forEach(day => {
                html += `<div class="calendar-day day-header">${day}</div>`;
            });

            // Empty cells before first day
            for(let i = 0; i < firstDay; i++) {
                html += '<div class="calendar-day"></div>';
            }

            // Days of month
            for(let day = 1; day <= daysInMonth; day++) {
                const dateStr= `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                const dayOfWeek = new Date(year, month, day).getDay();
                const isFuture = new Date(year, month, day) > today;
                const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;

                let className = 'calendar-day';
                let content = day;
                let tooltip = '';

                if(isFuture) {
                    className += ' day-future';
                } else if(isWeekend) {
                    className += ' day-weekend';
                } else {
                    // Find attendance record for this date
                    const record = attendanceData.find(r => r.attendance_date === dateStr);
                    
                    if(record) {
                        className += ' day-' + record.status.toLowerCase();
                        tooltip = `title="${record.status}${record.remarks ? ': ' + record.remarks : ''}"`;
                        //Show first letter of status for better visual indication
                        content = record.status.charAt(0).toUpperCase();
                    }
               }

                html += `<div class="${className}" ${tooltip}>${content}</div>`;
            }

            $('#calendar-grid').html(html);
        }

        function submitLeaveRequest() {
            const formData=$('#leave-request-form').serialize() + '&student_id=' + studentId;

            $('#submit-leave-btn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Submitting...');

            $.ajax({
                url: 'api/submit-leave-request.php',
               type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        $('#leaveModal').modal('hide');
                        $('#leave-request-form')[0].reset();
                        alert('Leave request submitted successfully! You will be notified once it is reviewed.');
                    } else{
                        alert('Error: ' + response.message);
                    }
                },
                error: function() {
                    alert('Error submitting request. Please try again.');
                },
                complete: function() {
                    $('#submit-leave-btn').prop('disabled', false).html('<i class="fas fa-paper-plane"></i>Submit Request');
                }
            });
        }
    </script>


    <script>
        $(document).ready(function(){
            $('.select2').select2();

        })

    </script>


    <?php
    }else{
    ?>
    <!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, maximum-scale=1, shrink-to-fit=no">


        <?php include '../admin/includes/styles.php'; ?>
<title>Login tocontinue </title>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </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 $student_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

    ?>
