<?php
/**
 * Direct database check for module status
 */

// Database configuration - you'll need to update these with your actual database credentials
$db_config = [
    'hostname' => 'localhost', // Update with your DB host
    'username' => 'root',      // Update with your DB username
    'password' => '',          // Update with your DB password
    'database' => 'perfex_crm' // Update with your DB name
];

echo "Direct database check for API module...\n\n";

try {
    // Connect to database
    $conn = new mysqli($db_config['hostname'], $db_config['username'], $db_config['password'], $db_config['database']);

    if ($conn->connect_error) {
        die("❌ Database connection failed: " . $conn->connect_error . "\n");
    }

    echo "✅ Connected to database successfully\n";

    // Check if modules table exists
    $result = $conn->query("SHOW TABLES LIKE 'modules'");
    if ($result->num_rows > 0) {
        echo "✅ modules table exists\n";

        // Check API module status
        $result = $conn->query("SELECT * FROM modules WHERE module_name = 'api'");
        if ($result->num_rows > 0) {
            $module = $result->fetch_assoc();
            echo "API module found in database:\n";
            echo "- ID: " . $module['id'] . "\n";
            echo "- Module Name: " . $module['module_name'] . "\n";
            echo "- Active: " . ($module['active'] ? 'YES' : 'NO') . "\n";
            echo "- Installed Version: " . $module['installed_version'] . "\n";

            if (!$module['active']) {
                echo "\n🔧 Activating API module...\n";
                $conn->query("UPDATE modules SET active = 1 WHERE module_name = 'api'");
                echo "✅ API module activated in database\n";
            } else {
                echo "\n✅ API module is already active\n";
            }
        } else {
            echo "❌ API module not found in database\n";

            // Try to insert it
            echo "🔧 Inserting API module into database...\n";
            $sql = "INSERT INTO modules (module_name, installed_version, active) VALUES ('api', '2.1.0', 1)";
            if ($conn->query($sql) === TRUE) {
                echo "✅ API module inserted and activated\n";
            } else {
                echo "❌ Failed to insert API module: " . $conn->error . "\n";
            }
        }

    } else {
        echo "❌ modules table does not exist\n";

        // Check what tables exist
        echo "Available tables:\n";
        $result = $conn->query("SHOW TABLES");
        while ($row = $result->fetch_array()) {
            echo "- " . $row[0] . "\n";
        }
    }

    $conn->close();

    echo "\n🎯 Next steps:\n";
    echo "1. Clear Perfex CRM cache\n";
    echo "2. Test API endpoints again\n";
    echo "3. If still not working, manually activate through admin panel\n";

} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n";
    echo "\n💡 Make sure to update the database credentials in this script!\n";
}
?>