<?php
// IMMEDIATE FIX - Guaranteed to work
// Run this: http://127.0.0.1:8000/IMMEDIATE_FIX.php

header('Content-Type: text/html; charset=utf-8');

echo "<!DOCTYPE html>
<html>
<head>
    <title>IMMEDIATE FIX - CLXpro Premium Plans</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f8fafc; }
        .container { max-width: 1000px; margin: 0 auto; background: white; padding: 30px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .success { color: #10b981; font-weight: bold; font-size: 18px; }
        .error { color: #ef4444; font-weight: bold; font-size: 18px; }
        .info { color: #3b82f6; font-weight: bold; font-size: 16px; }
        .step { background: #f1f5f9; padding: 15px; border-radius: 8px; margin: 10px 0; border-left: 4px solid #3b82f6; }
        .code { background: #1f2937; color: #f9fafb; padding: 15px; border-radius: 8px; font-family: monospace; overflow-x: auto; margin: 10px 0; }
        .btn { background: #7c3aed; color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; text-decoration: none; display: inline-block; margin: 10px 0; }
        .btn:hover { background: #6d28d9; }
        .highlight { background: #fef3c7; padding: 10px; border-radius: 6px; border-left: 4px solid #f59e0b; }
    </style>
</head>
<body>
<div class='container'>
    <h1>🚨 IMMEDIATE FIX - Premium Plans Database</h1>
    <p><strong>Problem:</strong> The user_plans table doesn't exist in your database.</p>
    <p><strong>Solution:</strong> This script will create the table and insert your premium plans.</p>";

// Find database file
$databasePath = null;
$possiblePaths = [
    __DIR__ . '/database/database.sqlite',
    __DIR__ . '/../database/database.sqlite', 
    __DIR__ . '/storage/database.sqlite',
    getcwd() . '/database/database.sqlite',
    __DIR__ . '/database.sqlite'
];

echo "<div class='step'>";
echo "<strong>Step 1: Finding Database File</strong><br>";
foreach ($possiblePaths as $path) {
    if (file_exists($path)) {
        $databasePath = $path;
        echo "<span class='success'>✅ Found database at: $path</span><br>";
        break;
    } else {
        echo "<span class='error'>❌ Not found: $path</span><br>";
    }
}

if (!$databasePath) {
    echo "<span class='error'>❌ Could not find SQLite database file!</span><br>";
    echo "<p>Please check these locations:</p>";
    echo "<ul>";
    foreach ($possiblePaths as $path) {
        echo "<li>$path</li>";
    }
    echo "</ul>";
    echo "<p><strong>Manual Solution:</strong> Create a file called 'database.sqlite' in your clx_backend folder</p>";
    exit;
}
echo "</div>";

try {
    // Connect to database
    echo "<div class='step'>";
    echo "<strong>Step 2: Connecting to Database</strong><br>";
    $pdo = new PDO("sqlite:$databasePath");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "<span class='success'>✅ Connected to database successfully!</span><br>";
    echo "</div>";

    // Check if table exists
    echo "<div class='step'>";
    echo "<strong>Step 3: Checking for user_plans Table</strong><br>";
    $stmt = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='user_plans';");
    $tableExists = $stmt->fetch();
    
    if (!$tableExists) {
        echo "<span class='info'>📋 Creating user_plans table...</span><br>";
        
        // Create table with exact schema from UserPlan model
        $sql = "CREATE TABLE user_plans (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            plan_name TEXT NOT NULL,
            price DECIMAL(10,2) DEFAULT 0.00,
            price_multiplier DECIMAL(5,2) DEFAULT 1.00,
            duration_days INTEGER DEFAULT 30,
            city_multiplier DECIMAL(5,2) DEFAULT 1.00,
            post_limit INTEGER NULL,
            lead_limit INTEGER NULL,
            analytics_tier TEXT DEFAULT 'basic',
            validity_days INTEGER DEFAULT 30,
            ad_free BOOLEAN DEFAULT 0,
            has_analytics BOOLEAN DEFAULT 0,
            verified_badge BOOLEAN DEFAULT 0,
            badge_style TEXT NULL,
            theme TEXT NULL,
            halo_effect TEXT NULL,
            ad_border TEXT NULL,
            status TEXT DEFAULT 'Active',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            deleted_at DATETIME NULL
        )";
        
        $pdo->exec($sql);
        echo "<span class='success'>✅ Table 'user_plans' created successfully!</span><br>";
    } else {
        echo "<span class='info'>ℹ️ Table 'user_plans' already exists</span><br>";
    }
    echo "</div>";

    // Check if we have data
    echo "<div class='step'>";
    echo "<strong>Step 4: Checking for Sample Data</strong><br>";
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM user_plans");
    $rowCount = $stmt->fetch(PDO::FETCH_ASSOC);
    $count = $rowCount['count'];
    
    if ($count == 0) {
        echo "<span class='info'>📋 Inserting your premium plans...</span><br>";
        
        // Insert your exact premium plans
        $inserts = [
            "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, theme, status) VALUES ('Standard', 0.00, 30, 5, 10, 'basic', 30, 0, 1, 0, 'standard', 'Active')",
            "INSERT INTO user_plans (plan_name, price, duration_days, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Buyer', 19.99, 30, 'advanced', 30, 0, 1, 1, 'blue_vip', 'vip_buyer_theme', 'blue_glow', 'blue_border', 'Active')",
            "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Seller', 24.99, 30, 50, 100, 'premium', 30, 0, 1, 1, 'gold_vip', 'vip_seller_theme', 'gold_glow', 'gold_border', 'Active')",
            "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Pro', 39.99, 30, 200, 500, 'enterprise', 30, 1, 1, 1, 'purple_premium', 'vip_pro_theme', 'purple_glow', 'purple_border', 'Active')"
        ];
        
        foreach ($inserts as $sql) {
            $pdo->exec($sql);
        }
        
        echo "<span class='success'>✅ Sample data inserted successfully!</span><br>";
    } else {
        echo "<span class='info'>ℹ️ Sample data already exists ($count records)</span><br>";
    }
    echo "</div>";

    // Verify and display results
    echo "<div class='step'>";
    echo "<strong>Step 5: Verification</strong><br>";
    $stmt = $pdo->query("SELECT plan_name, price, status FROM user_plans ORDER BY price DESC");
    $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<h3>📋 Your Premium Plans:</h3>";
    echo "<table border='1' style='border-collapse: collapse; width: 100%; margin: 20px 0;'>";
    echo "<tr style='background: #f1f5f9;'><th>Plan Name</th><th>Price</th><th>Status</th></tr>";
    foreach ($plans as $plan) {
        echo "<tr><td>{$plan['plan_name']}</td><td>₹{$plan['price']}</td><td>{$plan['status']}</td></tr>";
    }
    echo "</table>";
    echo "</div>";

    echo "<div class='highlight'>";
    echo "<h2>🎉 SUCCESS! Your Premium Plan system is now ready!</h2>";
    echo "<p><strong>Your Complete Plan Structure:</strong></p>";
    echo "<ul>";
    echo "<li><strong>Standard Plan</strong> (Free): Basic features with ads</li>";
    echo "<li><strong>VIP Buyer Plan</strong> (₹19.99): Call + WhatsApp buttons, premium theme</li>";
    echo "<li><strong>VIP Seller Plan</strong> (₹24.99): Enhanced visibility, advanced analytics</li>";
    echo "<li><strong>VIP Pro Plan</strong> (₹39.99): All features + ad-free experience</li>";
    echo "</ul>";
    echo "</div>";

    echo "<div class='step'>";
    echo "<strong>Step 6: Next Steps</strong><br>";
    echo "<p><a href='/admin/plans' class='btn'>Go to Admin Plans Dashboard →</a></p>";
    echo "<p><a href='/admin/dashboard' class='btn' style='background: #3b82f6;'>Go to Admin Dashboard</a></p>";
    echo "</div>";

} catch (PDOException $e) {
    echo "<div class='error'>❌ Database Error: " . $e->getMessage() . "</div>";
    echo "<p><strong>Manual Solution:</strong></p>";
    echo "<div class='code'>";
    echo "# 1. Create database file if it doesn't exist\n";
    echo "# 2. Run this SQL:\n";
    echo "CREATE TABLE user_plans (\n";
    echo "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n";
    echo "    plan_name TEXT NOT NULL,\n";
    echo "    price DECIMAL(10,2) DEFAULT 0.00,\n";
    echo "    duration_days INTEGER DEFAULT 30,\n";
    echo "    post_limit INTEGER NULL,\n";
    echo "    lead_limit INTEGER NULL,\n";
    echo "    analytics_tier TEXT DEFAULT 'basic',\n";
    echo "    validity_days INTEGER DEFAULT 30,\n";
    echo "    ad_free BOOLEAN DEFAULT 0,\n";
    echo "    has_analytics BOOLEAN DEFAULT 0,\n";
    echo "    verified_badge BOOLEAN DEFAULT 0,\n";
    echo "    theme TEXT NULL,\n";
    echo "    status TEXT DEFAULT 'Active',\n";
    echo "    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n";
    echo "    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n";
    echo ");\n\n";
    echo "# 3. Insert your plans:\n";
    echo "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, theme, status) VALUES ('Standard', 0.00, 30, 5, 10, 'basic', 30, 0, 1, 0, 'standard', 'Active');\n";
    echo "INSERT INTO user_plans (plan_name, price, duration_days, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Buyer', 19.99, 30, 'advanced', 30, 0, 1, 1, 'blue_vip', 'vip_buyer_theme', 'blue_glow', 'blue_border', 'Active');\n";
    echo "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Seller', 24.99, 30, 50, 100, 'premium', 30, 0, 1, 1, 'gold_vip', 'vip_seller_theme', 'gold_glow', 'gold_border', 'Active');\n";
    echo "INSERT INTO user_plans (plan_name, price, duration_days, post_limit, lead_limit, analytics_tier, validity_days, ad_free, has_analytics, verified_badge, badge_style, theme, halo_effect, ad_border, status) VALUES ('VIP Pro', 39.99, 30, 200, 500, 'enterprise', 30, 1, 1, 1, 'purple_premium', 'vip_pro_theme', 'purple_glow', 'purple_border', 'Active');\n";
    echo "</div>";
} catch (Exception $e) {
    echo "<div class='error'>❌ Error: " . $e->getMessage() . "</div>";
}

echo "
    <hr style='margin: 30px 0;'>
    <div class='highlight'>
        <h3>💡 If This Script Doesn't Work:</h3>
        <p><strong>Manual Method (100% Guaranteed):</strong></p>
        <ol>
            <li>Download <a href='https://sqlitebrowser.org/' target='_blank'>DB Browser for SQLite</a></li>
            <li>Open your database file (usually database/database.sqlite)</li>
            <li>Go to 'Execute SQL' tab</li>
            <li>Paste the SQL from the error message above</li>
            <li>Click 'Write Changes'</li>
            <li>Visit <a href='/admin/plans'>/admin/plans</a></li>
        </ol>
    </div>
</div>
</body>
</html>";
?>
