<?php
/**
 * Bank Management System Implementation Script
 * 
 * This script implements the complete bank management system
 * including database migration, menu registration, and setup.
 * 
 * Usage: php implement_bank_management.php
 */

// Include necessary files
require_once 'config.php';
require_once 'init.php';

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

echo "=== Bank Management System Implementation ===\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: Run database migration
    echo "1. Running database migration...\n";
    include 'migrate_bank_management.php';
    echo "   ✓ Database migration completed\n\n";
    
    // Step 2: Register bank management menu
    echo "2. Registering bank management menu...\n";
    
    // Check if menu already exists
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM tbl_appconfig WHERE setting = 'menu_banks'");
    $menu_exists = $stmt->fetch()['count'] > 0;
    
    if (!$menu_exists) {
        // Register bank management menu
        $menu_config = [
            'menu_banks' => 'Bank Management',
            'menu_banks_url' => 'banks/list',
            'menu_banks_icon' => 'fa fa-university',
            'menu_banks_order' => '50',
            'menu_banks_permission' => 'SuperAdmin,Admin'
        ];
        
        foreach ($menu_config as $key => $value) {
            $stmt = $pdo->prepare("INSERT INTO tbl_appconfig (setting, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?");
            $stmt->execute([$key, $value, $value]);
        }
        
        echo "   ✓ Bank management menu registered\n";
    } else {
        echo "   ✓ Bank management menu already exists\n";
    }
    
    // Step 3: Create bank management JavaScript file
    echo "3. Creating JavaScript file...\n";
    $js_content = '// Bank Management JavaScript
$(document).ready(function() {
    // Bank management specific JavaScript functions
    console.log("Bank Management System Loaded");
    
    // Add any bank-specific JavaScript here
});';
    
    $js_file = __DIR__ . '/ui/lib/c/banks.js';
    if (!file_exists($js_file)) {
        file_put_contents($js_file, $js_content);
        echo "   ✓ JavaScript file created\n";
    } else {
        echo "   ✓ JavaScript file already exists\n";
    }
    
    // Step 4: Verify implementation
    echo "4. Verifying implementation...\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 if banks exist
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM tbl_banks");
    $bank_count = $stmt->fetch()['count'];
    echo "   ✓ Found $bank_count banks in database\n";
    
    // Check STK Push configuration
    $stmt = $pdo->query("SELECT * FROM tbl_appconfig WHERE setting = 'Stkbankacc'");
    $stk_config = $stmt->fetch();
    if ($stk_config && is_numeric($stk_config['value'])) {
        echo "   ✓ BankStkPush configured with bank ID: {$stk_config['value']}\n";
    } else {
        echo "   ⚠ BankStkPush may need configuration\n";
    }
    
    // Step 5: Create usage documentation
    echo "5. Creating usage documentation...\n";
    $doc_content = '# Bank Management System

## Overview
The Bank Management System provides a professional interface for managing bank accounts used in STK Push payments.

## Features
- Add, edit, delete bank accounts
- Enable/disable STK Push support per bank
- Set default bank for STK Push
- Search and filter banks
- Professional admin interface

## Usage

### Access Bank Management
1. Login to admin panel
2. Navigate to "Bank Management" in the menu
3. Or go directly to: /admin/banks/list

### Add New Bank
1. Click "Add New Bank" button
2. Fill in bank details:
   - Bank Name (required)
   - Account Number (required)
   - Account Name (required)
   - Bank Code (optional)
   - Paybill Number (optional)
   - STK Push Support (checkbox)
   - Active Status (checkbox)
   - Set as Default (checkbox)

### Configure BankStkPush
1. Go to Payment Gateway settings
2. Select "BankStkPush"
3. Choose bank from dropdown
4. Save configuration

### Bank Management Actions
- **Edit**: Modify bank details
- **Set Default**: Make bank default for STK Push
- **Toggle Status**: Activate/deactivate bank
- **Delete**: Remove bank (if not in use)

## Database Structure

### tbl_banks table
- `id`: Primary key
- `name`: Bank name
- `paybill`: M-Pesa paybill number
- `account_number`: Bank account number
- `account_name`: Account holder name
- `bank_code`: Bank code (e.g., MPESA, EQTY)
- `supports_stk_push`: 1 if supports STK Push
- `is_active`: 1 if active
- `is_default`: 1 if default bank
- `created_at`: Creation timestamp
- `updated_at`: Last update timestamp

### tbl_appconfig settings
- `Stkbankacc`: Selected bank ID (not account number)
- `Stkbankname`: Selected bank name (for compatibility)

## API Endpoints
- `GET /admin/banks/api/get-active-banks`: Get banks with STK Push support
- `GET /admin/banks/api/get-bank-details`: Get specific bank details

## Security
- Role-based access control (SuperAdmin, Admin only)
- Input validation and sanitization
- CSRF protection
- Audit logging

## Troubleshooting

### No banks available in BankStkPush
1. Check if banks exist in Bank Management
2. Ensure banks have STK Push support enabled
3. Ensure banks are active

### Bank not found error
1. Verify bank exists in database
2. Check if bank is active
3. Check if bank supports STK Push

### Migration issues
1. Run restore script if needed
2. Check database permissions
3. Verify table structure

## Support
For issues or questions, check the logs and database structure.
';
    
    file_put_contents(__DIR__ . '/BANK_MANAGEMENT_README.md', $doc_content);
    echo "   ✓ Documentation created\n";
    
    echo "\n=== Implementation Completed Successfully! ===\n";
    echo "Next steps:\n";
    echo "1. Access admin panel and navigate to 'Bank Management'\n";
    echo "2. Add your bank accounts\n";
    echo "3. Configure BankStkPush to use the new system\n";
    echo "4. Test the payment flow\n\n";
    
    // Display current status
    echo "=== Current Status ===\n";
    
    // Show banks
    $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);
    
    if (empty($banks)) {
        echo "No banks found. Please add banks through the admin interface.\n";
    } else {
        echo "Current banks:\n";
        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";
        }
    }
    
    echo "\n=== Access URLs ===\n";
    echo "Bank Management: " . APP_URL . "/index.php?_route=banks/list\n";
    echo "BankStkPush Config: " . APP_URL . "/index.php?_route=paymentgateway/BankStkPush\n";
    
} catch (Exception $e) {
    echo "✗ Implementation failed: " . $e->getMessage() . "\n";
    echo "Please check the error and try again.\n";
    echo "You can restore from backup if needed.\n";
    exit(1);
}
?>
