<?php
/**
 * Bank Management System Migration Script
 * 
 * This script enhances the existing tbl_banks table and migrates
 * current BankStkPush configuration to the new system.
 * 
 * Usage: php migrate_bank_management.php
 */

// Include database configuration
require_once 'config.php';

// Set timezone
date_default_timezone_set('Africa/Nairobi');

echo "=== Bank Management System Migration ===\n";
echo "Database: $db_name\n";
echo "Started: " . date('Y-m-d H:i:s') . "\n\n";

try {
    // Create PDO connection
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "✓ Database connection established\n";
    
    // Step 1: Check if tbl_banks table exists
    echo "1. Checking tbl_banks table...\n";
    $stmt = $pdo->query("SHOW TABLES LIKE 'tbl_banks'");
    $table_exists = $stmt->fetch();
    
    if (!$table_exists) {
        echo "   Creating tbl_banks table...\n";
        $create_table_sql = "
        CREATE TABLE `tbl_banks` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `name` varchar(255) NOT NULL,
          `paybill` varchar(20) DEFAULT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        ";
        $pdo->exec($create_table_sql);
        echo "   ✓ tbl_banks table created\n";
    } else {
        echo "   ✓ tbl_banks table exists\n";
    }
    
    // Step 2: Enhance tbl_banks table with new columns
    echo "2. Enhancing tbl_banks table...\n";
    
    // Check if columns already exist
    $stmt = $pdo->query("SHOW COLUMNS FROM tbl_banks LIKE 'account_number'");
    $account_number_exists = $stmt->fetch();
    
    if (!$account_number_exists) {
        $alter_sql = "
        ALTER TABLE `tbl_banks` 
        ADD COLUMN `account_number` VARCHAR(50) NOT NULL DEFAULT '' AFTER `paybill`,
        ADD COLUMN `account_name` VARCHAR(255) NOT NULL DEFAULT '' AFTER `account_number`,
        ADD COLUMN `bank_code` VARCHAR(10) NOT NULL DEFAULT '' AFTER `account_name`,
        ADD COLUMN `supports_stk_push` TINYINT(1) NOT NULL DEFAULT 0 AFTER `bank_code`,
        ADD COLUMN `is_active` TINYINT(1) NOT NULL DEFAULT 1 AFTER `supports_stk_push`,
        ADD COLUMN `is_default` TINYINT(1) NOT NULL DEFAULT 0 AFTER `is_active`,
        ADD COLUMN `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP AFTER `is_default`,
        ADD COLUMN `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;
        ";
        
        $pdo->exec($alter_sql);
        echo "   ✓ New columns added to tbl_banks\n";
    } else {
        echo "   ✓ tbl_banks already enhanced\n";
    }
    
    // Step 3: Get current BankStkPush configuration
    echo "3. Reading current BankStkPush configuration...\n";
    $stmt = $pdo->query("SELECT setting, value FROM tbl_appconfig WHERE setting IN ('Stkbankacc', 'Stkbankname')");
    $current_config = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    $current_account = $current_config['Stkbankacc'] ?? '';
    $current_name = $current_config['Stkbankname'] ?? '';
    
    echo "   Current account: $current_account\n";
    echo "   Current bank name: $current_name\n";
    
    // Step 4: Create bank record from existing configuration
    if (!empty($current_account) && !empty($current_name)) {
        echo "4. Creating bank record from existing configuration...\n";
        
        // Check if bank already exists
        $stmt = $pdo->prepare("SELECT id FROM tbl_banks WHERE name = ? AND account_number = ?");
        $stmt->execute([$current_name, $current_account]);
        $existing_bank = $stmt->fetch();
        
        if (!$existing_bank) {
            $insert_sql = "
            INSERT INTO tbl_banks (name, paybill, account_number, account_name, supports_stk_push, is_active, is_default) 
            VALUES (?, ?, ?, ?, 1, 1, 1)
            ";
            $stmt = $pdo->prepare($insert_sql);
            $stmt->execute([
                $current_name,
                0, // Default paybill value
                $current_account,
                $current_name . ' Account' // Default account name
            ]);
            
            $bank_id = $pdo->lastInsertId();
            echo "   ✓ Bank record created with ID: $bank_id\n";
            
            // Step 5: Update appconfig to use bank ID
            echo "5. Updating appconfig to use bank ID...\n";
            $stmt = $pdo->prepare("UPDATE tbl_appconfig SET value = ? WHERE setting = 'Stkbankacc'");
            $stmt->execute([$bank_id]);
            echo "   ✓ Stkbankacc updated to bank ID: $bank_id\n";
            
        } else {
            $bank_id = $existing_bank['id'];
            echo "   ✓ Bank record already exists with ID: $bank_id\n";
            
            // Update existing bank to support STK Push
            $stmt = $pdo->prepare("UPDATE tbl_banks SET supports_stk_push = 1, is_active = 1 WHERE id = ?");
            $stmt->execute([$bank_id]);
            echo "   ✓ Bank record updated to support STK Push\n";
        }
    } else {
        echo "4. No existing BankStkPush configuration found\n";
        echo "   You can add banks through the admin interface\n";
    }
    
    // Step 6: Create sample banks if none exist
    echo "6. Checking for existing banks...\n";
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM tbl_banks");
    $bank_count = $stmt->fetch()['count'];
    
    if ($bank_count == 0) {
        echo "   Creating sample banks...\n";
        $sample_banks = [
            ['name' => 'Safaricom M-Pesa', 'account_number' => '1234567890', 'account_name' => 'M-Pesa Account', 'bank_code' => 'MPESA', 'supports_stk_push' => 1, 'is_active' => 1, 'is_default' => 1],
            ['name' => 'Equity Bank', 'account_number' => '0987654321', 'account_name' => 'Equity Account', 'bank_code' => 'EQTY', 'supports_stk_push' => 1, 'is_active' => 1, 'is_default' => 0],
            ['name' => 'KCB Bank', 'account_number' => '1122334455', 'account_name' => 'KCB Account', 'bank_code' => 'KCB', 'supports_stk_push' => 0, 'is_active' => 1, 'is_default' => 0]
        ];
        
        $insert_sql = "
        INSERT INTO tbl_banks (name, account_number, account_name, bank_code, supports_stk_push, is_active, is_default) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
        ";
        $stmt = $pdo->prepare($insert_sql);
        
        foreach ($sample_banks as $bank) {
            $stmt->execute([
                $bank['name'],
                $bank['account_number'],
                $bank['account_name'],
                $bank['bank_code'],
                $bank['supports_stk_push'],
                $bank['is_active'],
                $bank['is_default']
            ]);
        }
        
        echo "   ✓ Sample banks created\n";
    } else {
        echo "   ✓ Found $bank_count existing banks\n";
    }
    
    // Step 7: Verify migration
    echo "7. Verifying migration...\n";
    
    // Check tbl_banks structure
    $stmt = $pdo->query("DESCRIBE tbl_banks");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $required_columns = ['id', 'name', 'paybill', 'account_number', 'account_name', 'bank_code', 'supports_stk_push', 'is_active', 'is_default'];
    
    $missing_columns = array_diff($required_columns, $columns);
    if (empty($missing_columns)) {
        echo "   ✓ tbl_banks table structure is correct\n";
    } else {
        echo "   ✗ Missing columns: " . implode(', ', $missing_columns) . "\n";
    }
    
    // Check appconfig
    $stmt = $pdo->query("SELECT * FROM tbl_appconfig WHERE setting = 'Stkbankacc'");
    $stk_config = $stmt->fetch();
    if ($stk_config && is_numeric($stk_config['value'])) {
        echo "   ✓ Stkbankacc now contains bank ID: {$stk_config['value']}\n";
    } else {
        echo "   ⚠ Stkbankacc may need manual update\n";
    }
    
    // Check banks with STK Push support
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM tbl_banks WHERE supports_stk_push = 1 AND is_active = 1");
    $stk_banks = $stmt->fetch()['count'];
    echo "   ✓ Banks with STK Push support: $stk_banks\n";
    
    echo "\n=== Migration Completed Successfully! ===\n";
    echo "Next steps:\n";
    echo "1. Access the bank management interface at /admin/banks/\n";
    echo "2. Update BankStkPush configuration to use the new system\n";
    echo "3. Test the payment flow\n\n";
    
    // Display current banks
    echo "=== Current Banks ===\n";
    $stmt = $pdo->query("SELECT id, name, account_number, supports_stk_push, is_active, is_default FROM tbl_banks ORDER BY is_default DESC, name");
    $banks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($banks as $bank) {
        $status = $bank['is_active'] ? 'Active' : 'Inactive';
        $stk_support = $bank['supports_stk_push'] ? 'STK ✓' : 'STK ✗';
        $default = $bank['is_default'] ? ' (DEFAULT)' : '';
        echo "- ID: {$bank['id']}, {$bank['name']}, Account: {$bank['account_number']}, $status, $stk_support$default\n";
    }
    
} catch (Exception $e) {
    echo "✗ Migration failed: " . $e->getMessage() . "\n";
    echo "Please check the error and try again.\n";
    echo "You can restore from backup if needed.\n";
    exit(1);
}
?>
