<?php
require_once '../includes/config.php';

// Check if user is logged in and is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || $_SESSION['role'] !== 'admin') {
    header('Location: ../auth/login.php');
    exit();
}

$title = "Student Reports";

// Initialize variables
$message = '';
$message_type = '';

// Handle report generation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_report'])) {
    $report_type = $_POST['report_type'] ?? 'all';
    $status_filter = $_POST['status_filter'] ?? 'all';
    $year_level_filter = $_POST['year_level_filter'] ?? 'all';
    $course_filter = $_POST['course_filter'] ?? 'all';
    $date_from = $_POST['date_from'] ?? '';
    $date_to = $_POST['date_to'] ?? '';
    
    // Build query based on filters
    $sql = "SELECT s.*, g.name as gender, c.code as course_code, c.name as course_name, 
                   d.code as department_code, d.name as department_name,
                   sc.code as school_code, sc.name as school_name
            FROM students s
            LEFT JOIN genders g ON s.gender_id = g.id
            LEFT JOIN courses c ON s.course_id = c.id
            LEFT JOIN departments d ON s.department_id = d.id
            LEFT JOIN schools sc ON s.school_id = sc.id
            WHERE 1=1";
    
    if ($status_filter !== 'all') {
        $sql .= " AND s.status = " . intval($status_filter);
    }
    
    if ($year_level_filter !== 'all') {
        $sql .= " AND s.year_level = " . intval($year_level_filter);
    }
    
    if ($course_filter !== 'all') {
        $sql .= " AND s.course_id = " . intval($course_filter);
    }
    
    if (!empty($date_from)) {
        $sql .= " AND DATE(s.created_at) >= '" . escape($conn, $date_from) . "'";
    }
    
    if (!empty($date_to)) {
        $sql .= " AND DATE(s.created_at) <= '" . escape($conn, $date_to) . "'";
    }
    
    $sql .= " ORDER BY s.created_at DESC";
    
    $result = query($conn, $sql);
    $students = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $students[] = $row;
    }
    
    // Generate PDF
    if ($report_type === 'pdf') {
        require_once '../vendor/autoload.php'; // If using TCPDF or Dompdf
        
        // For now, we'll create a simple HTML report that can be printed
        // In production, you'd use a PDF library like TCPDF or Dompdf
        $_SESSION['report_data'] = [
            'students' => $students,
            'filters' => [
                'status' => $status_filter,
                'year_level' => $year_level_filter,
                'course' => $course_filter,
                'date_from' => $date_from,
                'date_to' => $date_to
            ]
        ];
        
        header('Location: print_report.php?type=pdf');
        exit();
    } 
    // Generate Excel
    elseif ($report_type === 'excel') {
        require_once '../includes/PHPExcel.php'; // Or use PhpSpreadsheet
        
        // Create Excel file
        $filename = "students_report_" . date('Y-m-d_H-i-s') . ".xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        // For now, create CSV as fallback
        outputCSV($students);
        exit();
    }
    // Print view
    elseif ($report_type === 'print') {
        $_SESSION['report_data'] = [
            'students' => $students,
            'filters' => [
                'status' => $status_filter,
                'year_level' => $year_level_filter,
                'course' => $course_filter,
                'date_from' => $date_from,
                'date_to' => $date_to
            ]
        ];
        
        header('Location: print_report.php');
        exit();
    }
}

// Get courses for filter dropdown
$courses = [];
$result = query($conn, "SELECT id, code, name FROM courses WHERE status = 1 ORDER BY code");
while ($row = mysqli_fetch_assoc($result)) {
    $courses[] = $row;
}

// Get departments
$departments = [];
$result = query($conn, "SELECT id, code, name FROM departments WHERE status = 1 ORDER BY code");
while ($row = mysqli_fetch_assoc($result)) {
    $departments[] = $row;
}

function outputCSV($data) {
    $output = fopen('php://output', 'w');
    
    // Header row
    fputcsv($output, [
        'Student ID', 'Full Name', 'Gender', 'Year Level', 'Course',
        'Department', 'Email', 'Contact Number', 'Status', 'Date Created'
    ]);
    
    // Data rows
    foreach ($data as $student) {
        fputcsv($output, [
            $student['student_id'],
            $student['full_name'],
            $student['gender'],
            'Year ' . $student['year_level'],
            $student['course_code'] . ' - ' . $student['course_name'],
            $student['department_name'],
            $student['email'],
            $student['contact_number'],
            $student['status'] == 1 ? 'Active' : 'Inactive',
            date('Y-m-d', strtotime($student['created_at']))
        ]);
    }
    
    fclose($output);
}

include '../includes/header.php';
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h3 mb-2">Student Reports</h1>
        <p class="text-muted">Generate and export student reports in various formats.</p>
    </div>
    <div>
        <a href="manage_students.php" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i> Back to Students
        </a>
    </div>
</div>

<!-- Message Alert -->
<?php if ($message): ?>
<div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
    <?php echo $message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Report Filters Card -->
<div class="card shadow mb-4">
    <div class="card-header">
        <h6 class="m-0 font-weight-bold">
            <i class="bi bi-filter me-2"></i> Report Filters
        </h6>
    </div>
    <div class="card-body">
        <form method="POST" action="">
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="form-label">Report Type</label>
                    <select class="form-select" name="report_type" required>
                        <option value="print">Print Preview</option>
                        <option value="pdf">PDF Document</option>
                        <option value="excel">Excel Spreadsheet</option>
                    </select>
                </div>
                
                <div class="col-md-3 mb-3">
                    <label class="form-label">Status</label>
                    <select class="form-select" name="status_filter">
                        <option value="all">All Status</option>
                        <option value="1">Active Only</option>
                        <option value="0">Inactive Only</option>
                    </select>
                </div>
                
                <div class="col-md-3 mb-3">
                    <label class="form-label">Year Level</label>
                    <select class="form-select" name="year_level_filter">
                        <option value="all">All Year Levels</option>
                        <?php for ($i = 1; $i <= 4; $i++): ?>
                            <option value="<?php echo $i; ?>">Year <?php echo $i; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                
                <div class="col-md-3 mb-3">
                    <label class="form-label">Course</label>
                    <select class="form-select" name="course_filter">
                        <option value="all">All Courses</option>
                        <?php foreach ($courses as $course): ?>
                            <option value="<?php echo $course['id']; ?>">
                                <?php echo $course['code']; ?> - <?php echo $course['name']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label class="form-label">Date From</label>
                    <input type="date" class="form-control" name="date_from">
                </div>
                
                <div class="col-md-6 mb-3">
                    <label class="form-label">Date To</label>
                    <input type="date" class="form-control" name="date_to">
                </div>
                
                <div class="col-12">
                    <div class="d-flex justify-content-end gap-2">
                        <button type="reset" class="btn btn-secondary">
                            <i class="bi bi-arrow-clockwise me-1"></i> Reset Filters
                        </button>
                        <button type="submit" name="generate_report" class="btn btn-primary">
                            <i class="bi bi-file-earmark-text me-1"></i> Generate Report
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Quick Export Options -->
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-body text-center">
                <i class="bi bi-printer text-primary mb-3" style="font-size: 3rem;"></i>
                <h5>Quick Print</h5>
                <p class="text-muted">Generate a printable student list</p>
                <form method="POST" action="">
                    <input type="hidden" name="report_type" value="print">
                    <input type="hidden" name="status_filter" value="all">
                    <button type="submit" name="generate_report" class="btn btn-outline-primary">
                        <i class="bi bi-printer me-1"></i> Print All Students
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-body text-center">
                <i class="bi bi-file-excel text-success mb-3" style="font-size: 3rem;"></i>
                <h5>Export Excel</h5>
                <p class="text-muted">Download as Excel spreadsheet</p>
                <form method="POST" action="">
                    <input type="hidden" name="report_type" value="excel">
                    <input type="hidden" name="status_filter" value="all">
                    <button type="submit" name="generate_report" class="btn btn-outline-success">
                        <i class="bi bi-download me-1"></i> Export to Excel
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-body text-center">
                <i class="bi bi-file-pdf text-danger mb-3" style="font-size: 3rem;"></i>
                <h5>PDF Report</h5>
                <p class="text-muted">Generate detailed PDF report</p>
                <form method="POST" action="">
                    <input type="hidden" name="report_type" value="pdf">
                    <input type="hidden" name="status_filter" value="all">
                    <button type="submit" name="generate_report" class="btn btn-outline-danger">
                        <i class="bi bi-file-earmark-pdf me-1"></i> Generate PDF
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php 
$page_scripts = '
<script>
$(document).ready(function() {
    // Set today as default date for "Date To"
    const today = new Date().toISOString().split("T")[0];
    $("input[name=\'date_to\']").val(today);
    
    // Set 30 days ago as default for "Date From"
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    $("input[name=\'date_from\']").val(thirtyDaysAgo.toISOString().split("T")[0]);
    
    // Form validation
    $("form").submit(function() {
        const dateFrom = $("input[name=\'date_from\']").val();
        const dateTo = $("input[name=\'date_to\']").val();
        
        if (dateFrom && dateTo && new Date(dateFrom) > new Date(dateTo)) {
            showNotification("Date From cannot be after Date To", "danger");
            return false;
        }
        
        showLoader("Generating report...");
        return true;
    });
});

// Quick export functions
function exportActiveStudents() {
    showConfirm("Export all active students to Excel?", function(confirmed) {
        if (confirmed) {
            const form = document.createElement("form");
            form.method = "POST";
            form.action = "";
            
            const typeInput = document.createElement("input");
            typeInput.type = "hidden";
            typeInput.name = "report_type";
            typeInput.value = "excel";
            form.appendChild(typeInput);
            
            const statusInput = document.createElement("input");
            statusInput.type = "hidden";
            statusInput.name = "status_filter";
            statusInput.value = "1";
            form.appendChild(statusInput);
            
            document.body.appendChild(form);
            form.submit();
        }
    });
}

function printStudentCards() {
    showConfirm("Generate printable student ID cards?", function(confirmed) {
        if (confirmed) {
            window.open("student_cards.php", "_blank");
        }
    });
}
</script>
';

include '../includes/footer.php';
?>