<?php
/**
 * Real-Time Dashboard Setup Verification
 * This file verifies all components are properly installed
 */

require_once 'config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'customer') {
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Verification - Login Required</title>
        <style>
            body { font-family: Arial, sans-serif; padding: 20px; }
            .alert { background: #fff3cd; border: 1px solid #ffc107; padding: 15px; border-radius: 5px; }
        </style>
    </head>
    <body>
        <div class="alert">
            <h3>⚠️ Login Required</h3>
            <p>Please <a href="login.php">login as a customer</a> to verify the setup.</p>
        </div>
    </body>
    </html>
    <?php
    exit;
}

$customer_id = $_SESSION['user_id'];
$verification_results = [];

// Function to check table exists
function check_table($conn, $table) {
    $result = $conn->query("SHOW TABLES LIKE '$table'");
    return $result && $result->num_rows > 0;
}

// Function to check column exists
function check_column($conn, $table, $column) {
    $result = $conn->query("SHOW COLUMNS FROM $table LIKE '$column'");
    return $result && $result->num_rows > 0;
}

// Function to check file exists
function check_file($path, $name = null) {
    if ($name === null) {
        $name = basename($path);
    }
    return file_exists($path);
}

// Perform all checks
$all_ok = true;

// Check 1: Database Tables
$tables = ['favorites', 'appointments', 'inquiries', 'users', 'properties'];
foreach ($tables as $table) {
    $exists = check_table($conn, $table);
    $verification_results[] = [
        'type' => 'Database Table',
        'item' => $table,
        'status' => $exists ? '✅' : '❌',
        'message' => $exists ? 'Table exists' : 'Table missing'
    ];
    if (!$exists) $all_ok = false;
}

// Check 2: Table Columns
$required_columns = [
    'favorites' => ['customer_id', 'property_id', 'created_at'],
    'appointments' => ['customer_id', 'property_id', 'appointment_date', 'appointment_time', 'status'],
    'inquiries' => ['customer_id', 'property_id', 'status', 'message'],
    'users' => ['phone', 'address']
];

foreach ($required_columns as $table => $columns) {
    foreach ($columns as $col) {
        $exists = check_column($conn, $table, $col);
        $verification_results[] = [
            'type' => 'Column',
            'item' => "$table.$col",
            'status' => $exists ? '✅' : '❌',
            'message' => $exists ? 'Column exists' : 'Column missing'
        ];
        if (!$exists) $all_ok = false;
    }
}

// Check 3: API Files
$api_files = [
    'favorites-toggle.php',
    'get-favorites.php',
    'appointment-add.php',
    'get-appointments.php',
    'schedule-visit.php',
    'inquiry-add.php',
    'get-inquiries.php',
    'profile-update.php',
    'get-profile.php'
];

foreach ($api_files as $file) {
    $path = __DIR__ . '/api/' . $file;
    $exists = check_file($path);
    $verification_results[] = [
        'type' => 'API File',
        'item' => $file,
        'status' => $exists ? '✅' : '❌',
        'message' => $exists ? 'File exists' : 'File missing'
    ];
    if (!$exists) $all_ok = false;
}

// Check 4: Data Access
try {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM favorites WHERE customer_id = ?");
    $stmt->bind_param('i', $customer_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $fav_count = $result['count'] ?? 0;
    $verification_results[] = [
        'type' => 'Data',
        'item' => 'Favorites count',
        'status' => '✅',
        'message' => $fav_count . ' favorite(s)'
    ];
    $stmt->close();
} catch (Exception $e) {
    $verification_results[] = [
        'type' => 'Data',
        'item' => 'Favorites count',
        'status' => '❌',
        'message' => $e->getMessage()
    ];
    $all_ok = false;
}

try {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE customer_id = ?");
    $stmt->bind_param('i', $customer_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $apt_count = $result['count'] ?? 0;
    $verification_results[] = [
        'type' => 'Data',
        'item' => 'Appointments count',
        'status' => '✅',
        'message' => $apt_count . ' appointment(s)'
    ];
    $stmt->close();
} catch (Exception $e) {
    $verification_results[] = [
        'type' => 'Data',
        'item' => 'Appointments count',
        'status' => '❌',
        'message' => $e->getMessage()
    ];
    $all_ok = false;
}

try {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM inquiries WHERE customer_id = ?");
    $stmt->bind_param('i', $customer_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $inq_count = $result['count'] ?? 0;
    $verification_results[] = [
        'type' => 'Data',
        'item' => 'Inquiries count',
        'status' => '✅',
        'message' => $inq_count . ' inquiry(ies)'
    ];
    $stmt->close();
} catch (Exception $e) {
    $verification_results[] = [
        'type' => 'Data',
        'item' => 'Inquiries count',
        'status' => '❌',
        'message' => $e->getMessage()
    ];
    $all_ok = false;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-Time Dashboard - Setup Verification</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Poppins', Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 40px 20px; }
        .container { max-width: 900px; margin: 0 auto; }
        .header { background: white; padding: 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); text-align: center; }
        .header h1 { font-size: 28px; color: #667eea; margin-bottom: 10px; }
        .header p { color: #666; }
        .status-badge { display: inline-block; padding: 10px 20px; border-radius: 20px; font-weight: 600; margin-top: 10px; }
        .status-ok { background: #d4edda; color: #155724; }
        .status-warning { background: #fff3cd; color: #856404; }
        .verification-box { background: white; border-radius: 10px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); overflow: hidden; }
        .section { border-bottom: 1px solid #eee; }
        .section:last-child { border-bottom: none; }
        .section-header { background: #f8f9fa; padding: 15px 30px; font-weight: 600; color: #333; border-bottom: 1px solid #ddd; }
        .verification-items { padding: 20px 30px; }
        .verification-item { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid #f0f0f0; }
        .verification-item:last-child { border-bottom: none; }
        .item-info { display: flex; align-items: center; gap: 15px; flex: 1; }
        .item-status { font-size: 20px; min-width: 30px; }
        .item-details { }
        .item-name { font-weight: 600; color: #333; }
        .item-message { font-size: 12px; color: #999; margin-top: 3px; }
        .item-type { background: #667eea; color: white; padding: 3px 10px; border-radius: 3px; font-size: 11px; font-weight: 600; }
        .actions { padding: 30px; background: white; border-radius: 10px; margin-top: 30px; text-align: center; }
        .button { display: inline-block; padding: 12px 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-decoration: none; border-radius: 5px; margin: 10px 10px 10px 0; font-weight: 600; border: none; cursor: pointer; transition: all 0.3s; }
        .button:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102,126,234,0.3); }
        .button-secondary { background: #6c757d; }
        .notes { background: #f0f7ff; border-left: 4px solid #667eea; padding: 20px; border-radius: 5px; margin-top: 30px; }
        .notes h3 { color: #667eea; margin-bottom: 10px; }
        .notes ul { margin-left: 20px; color: #555; line-height: 1.8; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>✨ Real-Time Dashboard Setup</h1>
            <p>Verification & Status Report</p>
            <div class="status-badge <?php echo $all_ok ? 'status-ok' : 'status-warning'; ?>">
                <?php echo $all_ok ? '✅ All Systems Ready' : '⚠️ Issues Detected'; ?>
            </div>
        </div>

        <div class="verification-box">
            <!-- Database Tables -->
            <div class="section">
                <div class="section-header">📊 Database Tables</div>
                <div class="verification-items">
                    <?php
                    foreach (array_filter($verification_results, fn($r) => $r['type'] === 'Database Table') as $result) {
                        echo '<div class="verification-item">';
                        echo '<div class="item-info">';
                        echo '<span class="item-status">' . $result['status'] . '</span>';
                        echo '<div class="item-details">';
                        echo '<div class="item-name">' . ucfirst($result['item']) . '</div>';
                        echo '<div class="item-message">' . $result['message'] . '</div>';
                        echo '</div></div>';
                        echo '<span class="item-type">TABLE</span>';
                        echo '</div>';
                    }
                    ?>
                </div>
            </div>

            <!-- Table Columns -->
            <div class="section">
                <div class="section-header">📋 Required Columns</div>
                <div class="verification-items">
                    <?php
                    foreach (array_filter($verification_results, fn($r) => $r['type'] === 'Column') as $result) {
                        echo '<div class="verification-item">';
                        echo '<div class="item-info">';
                        echo '<span class="item-status">' . $result['status'] . '</span>';
                        echo '<div class="item-details">';
                        echo '<div class="item-name">' . $result['item'] . '</div>';
                        echo '<div class="item-message">' . $result['message'] . '</div>';
                        echo '</div></div>';
                        echo '<span class="item-type">COLUMN</span>';
                        echo '</div>';
                    }
                    ?>
                </div>
            </div>

            <!-- API Files -->
            <div class="section">
                <div class="section-header">🔌 API Endpoints</div>
                <div class="verification-items">
                    <?php
                    foreach (array_filter($verification_results, fn($r) => $r['type'] === 'API File') as $result) {
                        echo '<div class="verification-item">';
                        echo '<div class="item-info">';
                        echo '<span class="item-status">' . $result['status'] . '</span>';
                        echo '<div class="item-details">';
                        echo '<div class="item-name">' . $result['item'] . '</div>';
                        echo '<div class="item-message">' . $result['message'] . '</div>';
                        echo '</div></div>';
                        echo '<span class="item-type">API</span>';
                        echo '</div>';
                    }
                    ?>
                </div>
            </div>

            <!-- Data Status -->
            <div class="section">
                <div class="section-header">📈 Your Data</div>
                <div class="verification-items">
                    <?php
                    foreach (array_filter($verification_results, fn($r) => $r['type'] === 'Data') as $result) {
                        echo '<div class="verification-item">';
                        echo '<div class="item-info">';
                        echo '<span class="item-status">' . $result['status'] . '</span>';
                        echo '<div class="item-details">';
                        echo '<div class="item-name">' . $result['item'] . '</div>';
                        echo '<div class="item-message">' . $result['message'] . '</div>';
                        echo '</div></div>';
                        echo '<span class="item-type">DATA</span>';
                        echo '</div>';
                    }
                    ?>
                </div>
            </div>
        </div>

        <div class="actions">
            <a href="dashboards/customer-dashboard.php" class="button">🚀 Go to Dashboard</a>
            <a href="properties.php" class="button button-secondary">🏠 Browse Properties</a>
        </div>

        <div class="notes">
            <h3>📝 Quick Notes:</h3>
            <ul>
                <li>✅ All API endpoints are in the <code>/api/</code> folder</li>
                <li>✅ Dashboard polls for updates every 5 seconds</li>
                <li>✅ Your data is synced in real-time across tabs</li>
                <li>📖 Read <strong>REALTIME_INTEGRATION_GUIDE.md</strong> for technical details</li>
                <li>📖 Read <strong>QUICKSTART_REALTIME.md</strong> for user guide</li>
                <li>🔧 For support, check browser console (F12) for error messages</li>
                <li>💡 All features are production-ready and secure</li>
            </ul>
        </div>
    </div>
</body>
</html>
