<?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> My Leave requests | <?php echo $school_name; ?> </title>

    <style>
        .request-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border-left: 5px solid;
            transition: transform 0.3s;
        }
        .request-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.15);
        }
        .request-card.pending { border-color: #ffc107; }
        .request-card.approved { border-color: #28a745; }
        .request-card.rejected { border-color: #dc3545; }

        .status-badge {
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9rem;
            display: inline-block;
        }
        .badge-pending { background: #fff3cd; color: #856404; }
        .badge-approved { background: #d4edda; color: #155724; }
        .badge-rejected { background: #f8d7da; color: #721c24; }

        .request-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
            gap: 10px;
        }
        .request-dates {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
        }
        .request-dates .row {
            margin-bottom: 10px;
        }
        .request-dates .row:last-child {
            margin-bottom: 0;
        }
        .date-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .date-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }
        .date-icon.start { background: #e3f2fd; color: #1976d2; }
        .date-icon.end { background: #fce4ec; color: #c2185b; }
        .date-icon.type { background: #f3e5f5; color: #7b1fa2; }

        .reason-box {
            background: #fff;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin: 15px 0;
        }
        .admin-response {
            background: #e7f3ff;
            border-left: 4px solid #007bff;
            padding: 15px;
            border-radius: 4px;
            margin-top: 15px;
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        .empty-icon {
            font-size: 5rem;
            color: #dee2e6;
            margin-bottom: 20px;
        }
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin: 10px 0;
        }
        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }
        .filter-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .filter-btn {
            padding: 10px 20px;
            border: 2px solid #dee2e6;
            background: white;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
        }
        .filter-btn:hover {
            background: #f8f9fa;
        }
        .filter-btn.active {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }
        .request-fab {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            font-size: 1.5rem;
            box-shadow: 0 4px 12px rgba(102,126,234,0.4);
            cursor: pointer;
            transition: all 0.3s;
            z-index: 1000;
        }
        .request-fab:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 16px rgba(102,126,234,0.6);
        }
    </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 Leave Requests </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 Leave Requests </li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->

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

                <?php
                // Get statistics
                $sql = "SELECT 
                        COUNT(*) as total,
                        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                        SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
                        SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected
                        FROM attendance_leave_requests 
                        WHERE student_id = :student_id";
                $conn->query($sql);
                $conn->bind(':student_id', $studentId);
                $stats = $conn->fetchSingle();
                ?>

                <!-- Statistics Cards -->
                <div class="stats-row">
                    <div class="stat-card" style="border-top: 4px solid #007bff;">
                        <i class="fas fa-file-alt" style="font-size: 2rem; color: #007bff;"></i>
                        <div class="stat-number" style="color: #007bff;"><?php echo $stats->total ?? 0; ?></div>
                        <div class="stat-label">Total Requests</div>
                    </div>

                    <div class="stat-card" style="border-top: 4px solid #ffc107;">
                        <i class="fas fa-clock" style="font-size: 2rem; color: #ffc107;"></i>
                        <div class="stat-number" style="color: #ffc107;"><?php echo $stats->pending ?? 0; ?></div>
                        <div class="stat-label">Pending</div>
                    </div>

                    <div class="stat-card" style="border-top: 4px solid #28a745;">
                        <i class="fas fa-check-circle" style="font-size: 2rem; color: #28a745;"></i>
                        <div class="stat-number" style="color: #28a745;"><?php echo $stats->approved ?? 0; ?></div>
                        <div class="stat-label">Approved</div>
                    </div>

                    <div class="stat-card" style="border-top: 4px solid #dc3545;">
                        <i class="fas fa-times-circle" style="font-size: 2rem; color: #dc3545;"></i>
                        <div class="stat-number" style="color: #dc3545;"><?php echo $stats->rejected ?? 0; ?></div>
                        <div class="stat-label">Rejected</div>
                    </div>
                </div>

                <!-- Filter Tabs -->
                <div class="filter-tabs">
                    <button class="filter-btn active" data-status="all">
                        <i class="fas fa-list"></i> All Requests
                    </button>
                    <button class="filter-btn" data-status="pending">
                        <i class="fas fa-clock"></i> Pending
                    </button>
                    <button class="filter-btn" data-status="approved">
                        <i class="fas fa-check"></i> Approved
                    </button>
                    <button class="filter-btn" data-status="rejected">
                        <i class="fas fa-times"></i> Rejected
                    </button>
                </div>

                <!-- Leave Requests List -->
                <div id="requests-container">
                    <?php
                    $sql = "SELECT * FROM attendance_leave_requests 
                            WHERE student_id = :student_id 
                            ORDER BY requested_at DESC";
                    $conn->query($sql);
                    $conn->bind(':student_id', $studentId);
                    $requests = $conn->fetchMultiple();

                    if($conn->rowCount() > 0) {
                        foreach($requests as $request) {
                            $statusClass = 'request-card ' . $request->status;
                            $badgeClass = 'status-badge badge-' . $request->status;

                            // Calculate days
                            $startDate = new DateTime($request->leave_from);
                            $endDate = new DateTime($request->leave_to);
                            $days = $startDate->diff($endDate)->days + 1;

                            echo '<div class="'.$statusClass.'" data-status="'.$request->status.'">
                                <div class="request-header">
                                    <div>
                                        <h5 style="margin: 0;">'.ucfirst($request->leave_type).' Leave</h5>
                                        <small class="text-muted">
                                            <i class="fas fa-clock"></i> Submitted on '.date('M d, Y', strtotime($request->created_at)).'
                                        </small>
                                    </div>
                                    <span class="'.$badgeClass.'">'.ucfirst($request->status).'</span>
                                </div>
                                
                                <div class="request-dates">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="date-info">
                                                <div class="date-icon start">
                                                    <i class="fas fa-play"></i>
                                                </div>
                                                <div>
                                                    <small class="text-muted">Start Date</small><br>
                                                    <strong>'.$startDate->format('M d, Y').'</strong>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="date-info">
                                                <div class="date-icon end">
                                                    <i class="fas fa-stop"></i>
                                                </div>
                                                <div>
                                                    <small class="text-muted">End Date</small><br>
                                                    <strong>'.$endDate->format('M d, Y').'</strong>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row" style="margin-top: 10px;">
                                        <div class="col-md-12">
                                            <div class="date-info">
                                                <div class="date-icon type">
                                                    <i class="fas fa-calendar"></i>
                                                </div>
                                                <div>
                                                    <small class="text-muted">Duration</small><br>
                                                    <strong>'.$days.' day'.($days > 1 ? 's' : '').'</strong>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="reason-box">
                                    <strong><i class="fas fa-comment"></i> Reason:</strong>
                                    <p style="margin: 10px 0 0 0; color: #555;">'.$request->reason.'</p>
                                </div>';

                            // Show admin response if processed
                            if($request->status != 'pending' && !empty($request->approval_comment)) {
                                $responseIcon = $request->status == 'approved' ? 'check-circle' : 'times-circle';
                                $responseColor = $request->status == 'approved' ? '#28a745' : '#dc3545';

                                echo '<div class="admin-response">
                                    <strong><i class="fas fa-'.$responseIcon.'" style="color: '.$responseColor.';"></i> Admin Response:</strong>
                                    <p style="margin: 10px 0 0 0;">'.$request->approval_comment.'</p>
                                    <small class="text-muted">
                                        <i class="fas fa-user"></i> '.($request->approved_by ?? 'System').' • 
                                        <i class="fas fa-clock"></i> '.($request->approved_at ? date('M d, Y h:i A', strtotime($request->approved_at)) : 'N/A').'
                                    </small>
                                </div>';
                            }

                            echo '</div>';
                        }
                    } else {
                        echo '<div class="empty-state">
                            <div class="empty-icon">
                                <i class="fas fa-calendar-times"></i>
                            </div>
                            <h4>No Leave Requests Yet</h4>
                            <p class="text-muted">Click the button below to submit your first leave request</p>
                        </div>';
                    }
                    ?>
                </div>

            </div>
        </section>

        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "../admin/includes/footer.php";?>
    <!-- Floating Action Button -->
    <button class="request-fab" data-toggle="modal" data-target="#leaveModal" title="New Leave Request">
        <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>Leave Type <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>
        $(document).ready(function() {
            // 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());
                }
            });

            // Filter tabs
            $('.filter-btn').on('click', function() {
                $('.filter-btn').removeClass('active');
                $(this).addClass('active');

                const status = $(this).data('status');

                if(status === 'all') {
                    $('.request-card').show();
                } else {
                    $('.request-card').hide();
                    $('.request-card[data-status="' + status + '"]').show();
                }
            });

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

        function submitLeaveRequest() {
            const formData = $('#leave-request-form').serialize() + '&student_id=<?php echo $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.');
                        location.reload();
                    } 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 to continue </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
    }

    ?>
