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

// Check database connection
if (!$pdo) {
    die("Database connection failed");
}

echo "<h1>Debug Tickets</h1>";

// Check if tickets table exists
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'tickets'");
    $table_exists = $stmt->fetch();
    if ($table_exists) {
        echo "<p>✓ Tickets table exists</p>";
    } else {
        echo "<p>✗ Tickets table does not exist</p>";
        exit;
    }
} catch (Exception $e) {
    echo "<p>Error checking table: " . $e->getMessage() . "</p>";
    exit;
}

// Count total tickets
try {
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM tickets");
    $count = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "<p>Total tickets in database: " . $count['count'] . "</p>";
    
    if ($count['count'] == 0) {
        echo "<p>No tickets found in database</p>";
    } else {
        // Get recent tickets directly
        $stmt = $pdo->query("SELECT t.*, tt.name as type_name, u.username as customer_name FROM tickets t LEFT JOIN ticket_types tt ON t.type_id = tt.id LEFT JOIN users u ON t.user_id = u.id ORDER BY t.created_at DESC LIMIT 10");
        $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo "<h2>Recent Tickets from Database:</h2>";
        if (!empty($tickets)) {
            echo "<ul>";
            foreach ($tickets as $ticket) {
                echo "<li>Ticket #" . $ticket['id'] . " - " . htmlspecialchars($ticket['subject']) . " - Status: " . $ticket['status'] . "</li>";
            }
            echo "</ul>";
        } else {
            echo "<p>No tickets found when querying directly</p>";
        }
        
        // Test the getRecentTickets function
        echo "<h2>Testing getRecentTickets function:</h2>";
        $recent_tickets = getRecentTickets($pdo, 10);
        if (!empty($recent_tickets)) {
            echo "<ul>";
            foreach ($recent_tickets as $ticket) {
                echo "<li>Ticket #" . $ticket['id'] . " - " . htmlspecialchars($ticket['subject']) . " - Status: " . $ticket['status'] . "</li>";
            }
            echo "</ul>";
        } else {
            echo "<p>getRecentTickets function returned empty array</p>";
        }
    }
} catch (Exception $e) {
    echo "<p>Error querying tickets: " . $e->getMessage() . "</p>";
}

// Check ticket types
echo "<h2>Ticket Types:</h2>";
try {
    $ticket_types = getTicketTypes($pdo);
    if (!empty($ticket_types)) {
        echo "<ul>";
        foreach ($ticket_types as $type) {
            echo "<li>" . htmlspecialchars($type['name']) . "</li>";
        }
        echo "</ul>";
    } else {
        echo "<p>No ticket types found</p>";
    }
} catch (Exception $e) {
    echo "<p>Error getting ticket types: " . $e->getMessage() . "</p>";
}
?>