<?php
/**
 * pay2inr System Diagnostic
 * Check if all required tables and columns exist
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once('../database/config.php');

$checks = [];
$allPassed = true;

// Check 1: Database Connection
try {
    $checks[] = [
        'name' => 'Database Connection',
        'status' => 'pass',
        'message' => 'Connected to database: ' . $dbname
    ];
} catch (Exception $e) {
    $checks[] = [
        'name' => 'Database Connection',
        'status' => 'fail',
        'message' => 'Failed to connect: ' . $e->getMessage()
    ];
    $allPassed = false;
}

// Check 2: create_orders table exists
try {
    $stmt = $conn->query("SHOW TABLES LIKE 'create_orders'");
    if ($stmt->rowCount() > 0) {
        $checks[] = [
            'name' => 'Table: create_orders',
            'status' => 'pass',
            'message' => 'Table exists'
        ];
    } else {
        $checks[] = [
            'name' => 'Table: create_orders',
            'status' => 'fail',
            'message' => 'Table does not exist'
        ];
        $allPassed = false;
    }
} catch (Exception $e) {
    $checks[] = [
        'name' => 'Table: create_orders',
        'status' => 'fail',
        'message' => $e->getMessage()
    ];
    $allPassed = false;
}

// Check 3: callback_logs table exists
try {
    $stmt = $conn->query("SHOW TABLES LIKE 'callback_logs'");
    if ($stmt->rowCount() > 0) {
        $checks[] = [
            'name' => 'Table: callback_logs',
            'status' => 'pass',
            'message' => 'Table exists'
        ];
    } else {
        $checks[] = [
            'name' => 'Table: callback_logs',
            'status' => 'fail',
            'message' => 'Table does not exist - Run database/create_callback_logs.sql'
        ];
        $allPassed = false;
    }
} catch (Exception $e) {
    $checks[] = [
        'name' => 'Table: callback_logs',
        'status' => 'fail',
        'message' => $e->getMessage()
    ];
    $allPassed = false;
}

// Check 4: Required columns in create_orders
$requiredColumns = ['api_txn_id', 'callback_sent'];
try {
    $stmt = $conn->query("DESCRIBE create_orders");
    $existingColumns = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $existingColumns[] = $row['Field'];
    }
    
    foreach ($requiredColumns as $col) {
        if (in_array($col, $existingColumns)) {
            $checks[] = [
                'name' => "Column: create_orders.$col",
                'status' => 'pass',
                'message' => 'Column exists'
            ];
        } else {
            $checks[] = [
                'name' => "Column: create_orders.$col",
                'status' => 'fail',
                'message' => 'Column missing - Run database/add_missing_columns.sql'
            ];
            $allPassed = false;
        }
    }
} catch (Exception $e) {
    $checks[] = [
        'name' => 'Columns Check',
        'status' => 'fail',
        'message' => $e->getMessage()
    ];
    $allPassed = false;
}

// Check 5: loginusers table
try {
    $stmt = $conn->query("SELECT COUNT(*) as count FROM loginusers");
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $checks[] = [
        'name' => 'Table: loginusers',
        'status' => 'pass',
        'message' => 'Table exists with ' . $result['count'] . ' users'
    ];
} catch (Exception $e) {
    $checks[] = [
        'name' => 'Table: loginusers',
        'status' => 'fail',
        'message' => $e->getMessage()
    ];
    $allPassed = false;
}

// Check 6: settings table
try {
    $stmt = $conn->query("SELECT * FROM settings LIMIT 1");
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($result) {
        $checks[] = [
            'name' => 'Table: settings',
            'status' => 'pass',
            'message' => 'Table exists with configuration'
        ];
    } else {
        $checks[] = [
            'name' => 'Table: settings',
            'status' => 'warn',
            'message' => 'Table exists but no data found'
        ];
    }
} catch (Exception $e) {
    $checks[] = [
        'name' => 'Table: settings',
        'status' => 'fail',
        'message' => $e->getMessage()
    ];
    $allPassed = false;
}

// Check 7: add_merchant table
try {
    $stmt = $conn->query("SELECT COUNT(*) as count FROM add_merchant WHERE status = 'Active'");
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($result['count'] > 0) {
        $checks[] = [
            'name' => 'Active Merchants',
            'status' => 'pass',
            'message' => $result['count'] . ' active merchant(s) found'
        ];
    } else {
        $checks[] = [
            'name' => 'Active Merchants',
            'status' => 'warn',
            'message' => 'No active merchants found - Add a merchant in admin panel'
        ];
    }
} catch (Exception $e) {
    $checks[] = [
        'name' => 'Active Merchants',
        'status' => 'fail',
        'message' => $e->getMessage()
    ];
}

// Check 8: RSPay configuration
try {
    require_once('../partner/rspay/config.php');
    if (isset($rspay_merchant_id) && isset($rspay_key)) {
        $checks[] = [
            'name' => 'RSPay Configuration',
            'status' => 'pass',
            'message' => 'RSPay credentials configured'
        ];
    } else {
        $checks[] = [
            'name' => 'RSPay Configuration',
            'status' => 'warn',
            'message' => 'RSPay credentials not found in config.php'
        ];
    }
} catch (Exception $e) {
    $checks[] = [
        'name' => 'RSPay Configuration',
        'status' => 'fail',
        'message' => $e->getMessage()
    ];
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>pay2inr System Diagnostic</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 10px;
            text-align: center;
        }
        
        .status-badge {
            display: inline-block;
            padding: 10px 20px;
            border-radius: 25px;
            font-weight: 600;
            margin: 20px auto;
            text-align: center;
            width: 100%;
        }
        
        .status-badge.pass {
            background: #d4edda;
            color: #155724;
        }
        
        .status-badge.fail {
            background: #f8d7da;
            color: #721c24;
        }
        
        .check-item {
            padding: 15px;
            margin: 10px 0;
            border-radius: 8px;
            border-left: 4px solid;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .check-item.pass {
            background: #d4edda;
            border-color: #28a745;
        }
        
        .check-item.fail {
            background: #f8d7da;
            border-color: #dc3545;
        }
        
        .check-item.warn {
            background: #fff3cd;
            border-color: #ffc107;
        }
        
        .check-icon {
            font-size: 24px;
            min-width: 30px;
        }
        
        .check-content {
            flex: 1;
        }
        
        .check-name {
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .check-message {
            font-size: 14px;
            opacity: 0.8;
        }
        
        .actions {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .actions h3 {
            margin-bottom: 15px;
            color: #333;
        }
        
        .actions ol {
            margin-left: 20px;
        }
        
        .actions li {
            margin: 10px 0;
            line-height: 1.6;
        }
        
        code {
            background: #e9ecef;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 pay2inr System Diagnostic</h1>
        
        <?php if ($allPassed): ?>
            <div class="status-badge pass">
                ✅ All Checks Passed - System Ready!
            </div>
        <?php else: ?>
            <div class="status-badge fail">
                ❌ Issues Found - Action Required
            </div>
        <?php endif; ?>
        
        <div style="margin-top: 30px;">
            <?php foreach ($checks as $check): ?>
                <div class="check-item <?= $check['status'] ?>">
                    <div class="check-icon">
                        <?php if ($check['status'] == 'pass'): ?>
                            ✅
                        <?php elseif ($check['status'] == 'warn'): ?>
                            ⚠️
                        <?php else: ?>
                            ❌
                        <?php endif; ?>
                    </div>
                    <div class="check-content">
                        <div class="check-name"><?= htmlspecialchars($check['name']) ?></div>
                        <div class="check-message"><?= htmlspecialchars($check['message']) ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <?php if (!$allPassed): ?>
            <div class="actions">
                <h3>🔧 Required Actions:</h3>
                <ol>
                    <li>Log into <strong>phpMyAdmin</strong> on your server</li>
                    <li>Select database: <code><?= htmlspecialchars($dbname) ?></code></li>
                    <li>Go to the <strong>SQL</strong> tab</li>
                    <li>Run the following SQL files in order:
                        <ul style="margin-top: 10px;">
                            <li><code>database/create_callback_logs.sql</code></li>
                            <li><code>database/add_missing_columns.sql</code></li>
                            <li><code>database/game_integration_setup.sql</code> (optional for games)</li>
                        </ul>
                    </li>
                    <li>Refresh this page to verify all checks pass</li>
                </ol>
            </div>
        <?php else: ?>
            <div class="actions">
                <h3>✅ Next Steps:</h3>
                <ol>
                    <li>Your system is ready to use!</li>
                    <li>Test the API: <a href="test-api.html" target="_blank">test-api.html</a></li>
                    <li>Read documentation: <code>API_REFERENCE.md</code></li>
                    <li>For game integration: <code>/pay/README.md</code></li>
                </ol>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
