<?php
/**
 * Test feedback display system
 * This script helps diagnose feedback display issues
 */

session_start();
require 'config.php';

// Display information about the request
header('Content-Type: text/html; charset=utf-8');

echo "<h1>Feedback Display Diagnostic</h1>";

// 1. Check database connection
echo "<h2>1. Database Connection</h2>";
if ($conn->connect_error) {
    echo "<p style='color: red;'>❌ Connection failed: " . $conn->connect_error . "</p>";
} else {
    echo "<p style='color: green;'>✅ Connected to database</p>";
}

// 2. Check feedback table
echo "<h2>2. Feedback Table Status</h2>";
$result = $conn->query("SELECT COUNT(*) as total FROM feedback");
if ($result) {
    $row = $result->fetch_assoc();
    echo "<p>Total feedback records: " . $row['total'] . "</p>";
} else {
    echo "<p style='color: red;'>❌ Error querying feedback table</p>";
}

// 3. Check approved feedback
echo "<h2>3. Approved Feedback Records</h2>";
$result = $conn->query("SELECT COUNT(*) as total FROM feedback WHERE status = 'approved'");
if ($result) {
    $row = $result->fetch_assoc();
    echo "<p>Approved feedback records: " . $row['total'] . "</p>";
    if ($row['total'] == 0) {
        echo "<p style='color: orange;'>⚠️ No approved feedback found. Admin needs to approve feedback first.</p>";
    }
} else {
    echo "<p style='color: red;'>❌ Error querying approved feedback</p>";
}

// 4. Check users table
echo "<h2>4. Users Table Status</h2>";
$result = $conn->query("SELECT COUNT(*) as total FROM users");
if ($result) {
    $row = $result->fetch_assoc();
    echo "<p>Total user records: " . $row['total'] . "</p>";
} else {
    echo "<p style='color: red;'>❌ Error querying users table</p>";
}

// 5. Test the API query
echo "<h2>5. API Query Test</h2>";
$sql = "SELECT f.id, f.message, f.rating, f.created_at, u.name as username 
        FROM feedback f
        JOIN users u ON f.user_id = u.id
        WHERE f.status = 'approved'
        ORDER BY f.created_at DESC
        LIMIT 10";

$result = $conn->query($sql);
if (!$result) {
    echo "<p style='color: red;'>❌ Query error: " . $conn->error . "</p>";
} else {
    $count = $result->num_rows;
    echo "<p>Query returned: " . $count . " records</p>";
    
    if ($count > 0) {
        echo "<table border='1' cellpadding='10'>";
        echo "<tr><th>ID</th><th>Username</th><th>Message</th><th>Rating</th><th>Date</th></tr>";
        while ($row = $result->fetch_assoc()) {
            echo "<tr>";
            echo "<td>" . htmlspecialchars($row['id']) . "</td>";
            echo "<td>" . htmlspecialchars($row['username']) . "</td>";
            echo "<td>" . htmlspecialchars(substr($row['message'], 0, 50)) . "...</td>";
            echo "<td>" . $row['rating'] . "</td>";
            echo "<td>" . $row['created_at'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
}

// 6. Sample feedback structure check
echo "<h2>6. Sample Feedback Data</h2>";
$result = $conn->query("SELECT f.* FROM feedback f LIMIT 1");
if ($result && $result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo "<pre>";
    print_r($row);
    echo "</pre>";
} else {
    echo "<p>No feedback records to display</p>";
}

// 7. Add test feedback if none exists
echo "<h2>7. Add Test Feedback</h2>";

// First check if test user exists
$testUserResult = $conn->query("SELECT id FROM users LIMIT 1");
if ($testUserResult && $testUserResult->num_rows > 0) {
    $testUser = $testUserResult->fetch_assoc();
    $userId = $testUser['id'];
    
    // Check if test feedback already exists
    $checkResult = $conn->query("SELECT id FROM feedback WHERE subject = 'Test Feedback' LIMIT 1");
    if ($checkResult && $checkResult->num_rows == 0) {
        // Add test feedback
        $testFeedback = [
            'user_id' => $userId,
            'subject' => 'Test Feedback',
            'message' => 'This is a test feedback to verify the display system is working correctly.',
            'rating' => 5,
            'status' => 'approved'
        ];
        
        $insertSql = "INSERT INTO feedback (user_id, subject, message, rating, status, created_at) 
                      VALUES (" . $userId . ", 'Test Feedback', 'This is a test feedback to verify the display system is working correctly.', 5, 'approved', NOW())";
        
        if ($conn->query($insertSql)) {
            echo "<p style='color: green;'>✅ Test feedback added successfully</p>";
        } else {
            echo "<p style='color: red;'>❌ Error adding test feedback: " . $conn->error . "</p>";
        }
    } else {
        echo "<p>Test feedback already exists</p>";
    }
} else {
    echo "<p style='color: orange;'>⚠️ No users found. Please create a user account first.</p>";
}

// 8. Test API JSON response
echo "<h2>8. API JSON Response Test</h2>";
$result = $conn->query("SELECT f.id, f.message, f.rating, f.created_at, u.name as username 
                        FROM feedback f
                        JOIN users u ON f.user_id = u.id
                        WHERE f.status = 'approved'
                        ORDER BY f.created_at DESC
                        LIMIT 10");

$reviews = [];
while ($row = $result->fetch_assoc()) {
    $reviews[] = $row;
}

$response = [
    'success' => true,
    'data' => $reviews,
    'count' => count($reviews)
];

echo "<pre>";
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
echo "</pre>";

echo "<h2>Summary</h2>";
echo "<p>If you see approved feedback in the API JSON Response section above, the system is working correctly.</p>";
echo "<p>Check your browser's developer console (F12) for any JavaScript errors.</p>";
echo "<p>If no approved feedback is shown, have an admin approve some feedback first in the admin panel.</p>";

$conn->close();
?>
