<?php
session_start();
require_once '../admin/includes/database.php';
$conn = new Database();

if(!isset($_SESSION['teacher'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

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

if (!$teacher) {
    header("Location: $teacher_login_link");
    exit();
}

$teacher_id = $teacher->id;
$teacher_name = $teacher->name;

//fetch teachers class id
$sql = "SELECT id FROM classes WHERE teacher_name = :teacher_name";
$conn->query($sql);
$conn->bind(':teacher_name', $teacher_name);
$teacher_class_id = $conn->fetchColumn();

$status = isset($_POST['status']) ? $_POST['status'] : 'pending';
$search = isset($_POST['search']) ? $_POST['search'] : '';
$classId = isset($_POST['class_id']) ? $_POST['class_id'] : '';
$dateRange = isset($_POST['date_range']) ? $_POST['date_range'] : '';

// Build query
$sql = "SELECT lr.*, s.name as student_name, s.registerNO, s.photo,
        c.name as class_name, sec.name as section_name
        FROM attendance_leave_requests lr
        JOIN student s ON lr.student_id = s.studentID
        LEFT JOIN classes c ON s.classesID = c.id
        LEFT JOIN sections sec ON s.sectionid = sec.id
        WHERE 1=1 AND s.classesID = :teacher_class_id";

// Status filter
if($status !== 'all') {
    $sql .= " AND lr.status = :status";
}

// Search filter
if(!empty($search)) {
    $sql .= " AND (s.name LIKE :search OR s.registerNO LIKE :search)";
}

// Class filter
if(!empty($classId)) {
    $sql .= " AND s.classesID = :class_id";
}

// Date range filter
if(!empty($dateRange)) {
    switch($dateRange) {
        case 'today':
            $sql .= " AND DATE(lr.requested_at) = CURDATE()";
            break;
        case 'week':
            $sql .= " AND YEARWEEK(lr.requested_at) = YEARWEEK(CURDATE())";
            break;
        case 'month':
            $sql .= " AND MONTH(lr.requested_at) = MONTH(CURDATE()) AND YEAR(lr.requested_at) = YEAR(CURDATE())";
            break;
    }
}

$sql .= " ORDER BY lr.requested_at DESC";

$conn->query($sql);
$conn->bind(':teacher_class_id', $teacher_class_id);

// Bind parameters
if($status !== 'all') {
    $conn->bind(':status', $status);
}
if(!empty($search)) {
    $conn->bind(':search', '%' . $search . '%');
}
if(!empty($classId)) {
    $conn->bind(':class_id', $classId);
}

$requests = $conn->fetchMultiple();

if($conn->rowCount() > 0) {
    foreach($requests as $request) {
        $statusBadge = '';
        $cardClass = 'request-pending';
        $actionButtons = '';

        switch($request->status) {
            case 'pending':
                $statusBadge = '<span class="badge badge-pending">Pending</span>';
                $cardClass = 'request-pending';
                $actionButtons = '
                    <div class="action-buttons">
                        <button class="btn btn-success approve-btn" data-id="'.$request->id.'">
                            <i class="fas fa-check"></i> Approve
                        </button>
                        <button class="btn btn-danger reject-btn" data-id="'.$request->id.'">
                            <i class="fas fa-times"></i> Reject
                        </button>
                    </div>';
                break;
            case 'approved':
                $statusBadge = '<span class="badge badge-approved">Approved</span>';
                $cardClass = 'request-approved';
                break;
            case 'rejected':
                $statusBadge = '<span class="badge badge-rejected">Rejected</span>';
                $cardClass = 'request-rejected';
                break;
        }

        $photoUrl = !empty($request->photo) ? '../admin/upload/' . $request->photo : '../admin/upload/default.png';

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

        $submittedTime = time_elapsed_string($request->requested_at);

        echo '
        <div class="request-card '.$cardClass.'">
            <div class="student-info">
                <img src="'.$photoUrl.'" alt="Student Photo" class="student-avatar">
                <div class="student-details">
                    <h5>'.$request->student_name.' '.$statusBadge.'</h5>
                    <small>
                        <i class="fas fa-id-card"></i> '.$request->registerNO.' &nbsp;|&nbsp;
                        <i class="fas fa-school"></i> '.$request->class_name.' - '.$request->section_name.' &nbsp;|&nbsp;
                        <i class="fas fa-clock"></i> '.$submittedTime.'
                    </small>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <strong><i class="fas fa-calendar-alt"></i> Leave Period:</strong><br>
                    '.$startDate->format('M d, Y').' to '.$endDate->format('M d, Y').'<br>
                    <small class="text-muted">('.$days.' day'.($days > 1 ? 's' : '').')</small>
                </div>
                <div class="col-md-6">
                    <strong><i class="fas fa-tag"></i> Leave Type:</strong><br>
                    '.ucfirst($request->leave_type).'
                </div>
            </div>
            
            <div style="margin-top: 15px;">
                <strong><i class="fas fa-comment"></i> Reason:</strong><br>
                <p style="margin: 5px 0; color: #555;">'.$request->reason.'</p>
            </div>';

        // Show approval/rejection details if processed
        if($request->status !== 'pending') {
            $processedBy = $request->approved_by ?: 'System';
            $processedDate = $request->approved_at ? date('M d, Y h:i A', strtotime($request->approved_at)) : 'N/A';

            echo '
            <div class="leave-details" style="display:block; margin-top:15px;">
                <div class="row">
                    <div class="col-md-6">
                        <strong>'.ucfirst($request->status).' By:</strong> '.$processedBy.'
                    </div>
                    <div class="col-md-6">
                        <strong>'.ucfirst($request->status).' On:</strong> '.$processedDate.'
                    </div>
                </div>';

            if(!empty($request->approval_comment)) {
                echo '
                <div style="margin-top: 10px;">
                    <strong>Admin Remarks:</strong><br>
                    <p style="margin: 5px 0; color: #555;">'.$request->approval_comment.'</p>
                </div>';
            }

            echo '</div>';
        }

        // Show action buttons for pending requests
        if($request->status === 'pending') {
            echo '<div style="margin-top: 15px;">'.$actionButtons.'</div>';
        }

        echo '</div>';
    }
} else {
    $message = 'No leave requests found';
    if($status !== 'all') {
        $message .= ' with status: <strong>'.ucfirst($status).'</strong>';
    }
    echo '<div class="alert alert-info text-center">
            <i class="fas fa-info-circle"></i> '.$message.'
          </div>';
}

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';
}
