<?php
/**
 * Migration Script: Payment System & Subscriptions
 */

declare(strict_types=1);

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

use App\Core\Database;

$db = Database::getInstance();

try {
    echo "Starting migration...\n";

    // 1. Create subscription_plans table
    echo "Creating subscription_plans table...\n";
    $db->exec("
        CREATE TABLE IF NOT EXISTS subscription_plans (
            id VARCHAR(50) PRIMARY KEY,
            name_ar VARCHAR(255) NOT NULL,
            name_en VARCHAR(255) NOT NULL,
            max_companies INT NOT NULL,
            max_invoices_month INT NOT NULL,
            max_users INT NOT NULL,
            price_jod DECIMAL(10,3) NOT NULL,
            ai_features BOOLEAN DEFAULT TRUE,
            jofotara_enabled BOOLEAN DEFAULT TRUE,
            sort_order INT DEFAULT 0,
            is_active BOOLEAN DEFAULT TRUE,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    // 2. Insert initial plans
    echo "Inserting initial plans...\n";
    $plans = require __DIR__ . '/../app/config/plans.php';
    $stmt = $db->prepare("
        INSERT INTO subscription_plans (id, name_ar, name_en, max_companies, max_invoices_month, max_users, price_jod, ai_features, jofotara_enabled, sort_order)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
            name_ar = VALUES(name_ar), 
            price_jod = VALUES(price_jod),
            max_companies = VALUES(max_companies),
            max_invoices_month = VALUES(max_invoices_month)
    ");

    $order = 0;
    foreach ($plans as $id => $plan) {
        $stmt->execute([
            $id,
            $plan['name_ar'],
            $plan['name_en'],
            $plan['max_companies'],
            $plan['max_invoices_month'],
            $plan['max_users'],
            $plan['price_jod'],
            $plan['ai_features'] ? 1 : 0,
            $plan['jofotara_enabled'] ? 1 : 0,
            $order++
        ]);
    }

    // 3. Create payment_requests table
    echo "Creating payment_requests table...\n";
    $db->exec("
        CREATE TABLE IF NOT EXISTS payment_requests (
            id CHAR(36) PRIMARY KEY,
            tenant_id CHAR(36) NOT NULL,
            user_id CHAR(36) NOT NULL,
            plan_id VARCHAR(50) NOT NULL,
            amount_jod DECIMAL(10,3) NOT NULL,
            internal_reference VARCHAR(50) UNIQUE NOT NULL,
            cliq_alias VARCHAR(100) NOT NULL,
            payer_name VARCHAR(255) DEFAULT NULL,
            bank_reference VARCHAR(100) DEFAULT NULL,
            status ENUM('pending','uploaded','verified','approved','rejected') DEFAULT 'pending',
            admin_notes TEXT DEFAULT NULL,
            verified_at DATETIME DEFAULT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (tenant_id) REFERENCES tenants(id),
            FOREIGN KEY (user_id) REFERENCES users(id),
            INDEX idx_status (status),
            INDEX idx_bank_ref (bank_reference)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    // 4. Create bank_transactions table
    echo "Creating bank_transactions table...\n";
    $db->exec("
        CREATE TABLE IF NOT EXISTS bank_transactions (
            id INT AUTO_INCREMENT PRIMARY KEY,
            bank_reference VARCHAR(100) UNIQUE NOT NULL,
            amount DECIMAL(10,3) NOT NULL,
            sender_name VARCHAR(255) DEFAULT NULL,
            raw_message TEXT NOT NULL,
            is_claimed BOOLEAN DEFAULT FALSE,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_ref (bank_reference)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    // 5. Update subscriptions table if needed
    echo "Updating subscriptions table schema...\n";
    // Check if column plan_id exists, if not add it
    $cols = $db->query("SHOW COLUMNS FROM subscriptions")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('plan_id', $cols)) {
        $db->exec("ALTER TABLE subscriptions ADD COLUMN plan_id VARCHAR(50) AFTER tenant_id");
        $db->exec("ALTER TABLE subscriptions MODIFY COLUMN plan ENUM('free','basic','office','pro','enterprise') DEFAULT 'free'");
    }
    if (!in_array('max_users', $cols)) {
        $db->exec("ALTER TABLE subscriptions ADD COLUMN max_users INT NOT NULL DEFAULT 1 AFTER max_invoices_per_month");
    }

    echo "Migration completed successfully!\n";

} catch (\Throwable $e) {
    echo "Migration failed: " . $e->getMessage() . "\n";
    exit(1);
}
