<?php
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit('Access denied.');
}

require_once __DIR__ . '/app/bootstrap.php';

use App\Core\Database;

try {
    $pdo = Database::getConnection();

    echo "=== Seeding Default Subscription Plans ===\n";

    $plans = [
        [
            'id' => 1,
            'name' => 'Starter',
            'price' => 19.00,
            'max_sessions' => 1,
            'max_requests' => 1000,
            'max_voice_requests' => 0,
            'max_ocr_requests' => 0,
            'features' => json_encode(['text_chatbot' => true, 'campaigns' => true])
        ],
        [
            'id' => 2,
            'name' => 'Growth',
            'price' => 49.00,
            'max_sessions' => 2,
            'max_requests' => 5000,
            'max_voice_requests' => 500,
            'max_ocr_requests' => 500,
            'features' => json_encode(['text_chatbot' => true, 'campaigns' => true, 'woocommerce' => true, 'salla' => true])
        ],
        [
            'id' => 3,
            'name' => 'Professional',
            'price' => 99.00,
            'max_sessions' => 5,
            'max_requests' => 15000,
            'max_voice_requests' => 2000,
            'max_ocr_requests' => 2000,
            'features' => json_encode(['text_chatbot' => true, 'campaigns' => true, 'woocommerce' => true, 'salla' => true, 'webhooks' => true, 'voice' => true])
        ],
        [
            'id' => 4,
            'name' => 'Trial (14 Days)',
            'price' => 0.00,
            'max_sessions' => 1,
            'max_requests' => 5000,
            'max_voice_requests' => 100,
            'max_ocr_requests' => 100,
            'features' => json_encode(['text_chatbot' => true, 'campaigns' => true, 'woocommerce' => true, 'salla' => true, 'webhooks' => true, 'voice' => true])
        ]
    ];

    foreach ($plans as $p) {
        Database::execute("
            INSERT INTO subscription_plans (id, name, price, max_sessions, max_requests, max_voice_requests, max_ocr_requests, features)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE 
                name = VALUES(name), 
                price = VALUES(price), 
                max_sessions = VALUES(max_sessions), 
                max_requests = VALUES(max_requests), 
                max_voice_requests = VALUES(max_voice_requests), 
                max_ocr_requests = VALUES(max_ocr_requests),
                features = VALUES(features)
        ", [
            $p['id'],
            $p['name'],
            $p['price'],
            $p['max_sessions'],
            $p['max_requests'],
            $p['max_voice_requests'],
            $p['max_ocr_requests'],
            $p['features']
        ]);
        echo "✅ Seeded/Updated Plan: {$p['name']} (ID: {$p['id']})\n";
    }

    // Check if the user specified a company to subscribe
    global $argv;
    if (isset($argv[1])) {
        $companyId = (int)$argv[1];
        $planId = isset($argv[2]) ? (int)$argv[2] : 2; // Default to Growth Plan (ID 2)

        echo "\n=== Subscribing Company ID: $companyId to Plan ID: $planId ===\n";

        // Check if company exists
        $companyExists = Database::selectOne("SELECT id FROM companies WHERE id = ?", [$companyId]);
        if (!$companyExists) {
            echo "⚠️ Company ID $companyId does not exist in database. Creating it...\n";
            Database::execute("INSERT INTO companies (id, name) VALUES (?, ?)", [$companyId, "Merchant Company $companyId"]);
        }

        // Subscribing
        $startsAt = date('Y-m-d H:i:s');
        $endsAt = date('Y-m-d H:i:s', strtotime('+30 days'));

        // Delete existing subscriptions for this company
        Database::execute("DELETE FROM company_subscriptions WHERE company_id = ?", [$companyId]);
        
        Database::execute("
            INSERT INTO company_subscriptions (company_id, plan_id, status, starts_at, ends_at)
            VALUES (?, ?, 'active', ?, ?)
        ", [$companyId, $planId, $startsAt, $endsAt]);

        // Clean cache for this company subscription
        if (class_exists('App\Core\Cache')) {
            \App\Core\Cache::delete("company_subscription:{$companyId}");
            \App\Core\Cache::delete("company_subscription_usage:{$companyId}:" . date('Y-m-d', strtotime($startsAt)));
        }

        echo "✅ Company ID $companyId successfully subscribed to Plan ID $planId until $endsAt.\n";
    } else {
        echo "\n💡 Tip: You can subscribe a company to a plan by passing company_id and plan_id as arguments:\n";
        echo "   php seed_default_plans.php [company_id] [plan_id]\n";
        echo "   Example: php seed_default_plans.php 1 2 (subscribes company ID 1 to Growth plan)\n";
    }

} catch (\Exception $e) {
    echo "❌ Error seeding data: " . $e->getMessage() . "\n";
}
