<?php
session_start();
require_once 'config/database.php';

echo "<h2>Debugging Income Report Page</h2>";

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo "<p>❌ User not logged in - redirecting to login</p>";
    // Don't redirect in debug mode
} else {
    echo "<p>✅ User logged in with ID: " . $_SESSION['user_id'] . "</p>";
}

// Test database connection
try {
    echo "<h3>Database Connection Test:</h3>";
    $pdo->query("SELECT 1");
    echo "<p>✅ Database connection successful</p>";
} catch (Exception $e) {
    echo "<p>❌ Database connection failed: " . $e->getMessage() . "</p>";
    exit;
}

// Test required tables
echo "<h3>Table Existence Check:</h3>";
$tables = ['fee_payments', 'fees', 'students', 'users'];
foreach ($tables as $table) {
    try {
        $stmt = $pdo->prepare("SHOW TABLES LIKE ?");
        $stmt->execute([$table]);
        $result = $stmt->fetchAll();
        if (count($result) > 0) {
            echo "<p>✅ Table '$table' exists</p>";
        } else {
            echo "<p>❌ Table '$table' NOT FOUND</p>";
        }
    } catch (Exception $e) {
        echo "<p>❌ Error checking table '$table': " . $e->getMessage() . "</p>";
    }
}

// Test the main query from income_report.php
echo "<h3>Query Test:</h3>";
try {
    $start_date = date('Y-m-01');
    $end_date = date('Y-m-t');
    
    $sql = "SELECT fp.*, f.title as fee_title, s.student_name, s.class, s.roll_number, u.username as collected_by_name 
            FROM fee_payments fp 
            LEFT JOIN fees f ON fp.fee_id = f.id 
            LEFT JOIN students s ON fp.student_id = s.id 
            LEFT JOIN users u ON fp.created_by = u.id 
            WHERE fp.payment_date BETWEEN ? AND ?
            ORDER BY fp.payment_date DESC, fp.id DESC
            LIMIT 5";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$start_date, $end_date]);
    $results = $stmt->fetchAll();
    
    echo "<p>✅ Main query executed successfully</p>";
    echo "<p>Found " . count($results) . " records</p>";
    
    if (!empty($results)) {
        echo "<h4>Sample Data:</h4>";
        echo "<pre>";
        print_r($results[0]);
        echo "</pre>";
    }
    
} catch (Exception $e) {
    echo "<p>❌ Query failed: " . $e->getMessage() . "</p>";
    echo "<p>SQL: " . $sql . "</p>";
}

echo "<h3>Session Data:</h3>";
echo "<pre>";
print_r($_SESSION);
echo "</pre>";

echo "<p><a href='fees/income_report.php'>Try accessing the income report page</a></p>";
?>