<?php
/**
 * Script para crear un cliente de ejemplo con datos completos
 * para probar el dashboard del cliente
 */

require_once __DIR__ . '/database/config.php';
require_once __DIR__ . '/database/connection.php';

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    
    // Iniciar transacción
    $pdo->beginTransaction();
    
    // 1. Crear cliente de ejemplo
    $clientData = [
        'email' => 'cliente.demo@example.com',
        'first_name' => 'Carlos',
        'last_name' => 'Mendoza',
        'phone' => '+34 666 777 888',
        'status' => 'active',
        'password_hash' => password_hash('demo123', PASSWORD_DEFAULT)
    ];
    
    // Verificar si el cliente ya existe
    $checkStmt = $pdo->prepare("SELECT id FROM clients WHERE email = ?");
    $checkStmt->execute([$clientData['email']]);
    
    if ($checkStmt->fetch()) {
        echo "El cliente ya existe. Actualizando datos...\n";
        
        // Actualizar cliente existente
        $updateStmt = $pdo->prepare("
            UPDATE clients 
            SET first_name = ?, last_name = ?, phone = ?, status = ?, password_hash = ?, updated_at = NOW()
            WHERE email = ?
        ");
        $updateStmt->execute([
            $clientData['first_name'],
            $clientData['last_name'], 
            $clientData['phone'],
            $clientData['status'],
            $clientData['password_hash'],
            $clientData['email']
        ]);
        
        // Obtener ID del cliente
        $clientStmt = $pdo->prepare("SELECT id FROM clients WHERE email = ?");
        $clientStmt->execute([$clientData['email']]);
        $clientId = $clientStmt->fetchColumn();
        
    } else {
        // Insertar nuevo cliente
        $insertStmt = $pdo->prepare("
            INSERT INTO clients (email, first_name, last_name, phone, status, password_hash, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
        ");
        $insertStmt->execute([
            $clientData['email'],
            $clientData['first_name'],
            $clientData['last_name'],
            $clientData['phone'],
            $clientData['status'],
            $clientData['password_hash']
        ]);
        
        $clientId = $pdo->lastInsertId();
        echo "Cliente creado con ID: $clientId\n";
    }
    
    // 2. Limpiar cuentas existentes del cliente
    $pdo->prepare("DELETE FROM client_accounts WHERE client_id = ?")->execute([$clientId]);
    $pdo->prepare("DELETE FROM client_deposits WHERE client_id = ?")->execute([$clientId]);
    $pdo->prepare("DELETE FROM client_transactions WHERE client_id = ?")->execute([$clientId]);
    
    // 3. Crear cuentas de ejemplo
    $accounts = [
        [
            'account_type' => 'Standard',
            'account_number' => 'STD-' . str_pad($clientId, 6, '0', STR_PAD_LEFT) . '-001',
            'currency' => 'USD',
            'balance' => 15750.50,
            'provider' => 'MetaTrader 4',
            'status' => 'active'
        ],
        [
            'account_type' => 'Premium',
            'account_number' => 'PRM-' . str_pad($clientId, 6, '0', STR_PAD_LEFT) . '-002',
            'currency' => 'EUR',
            'balance' => 8920.75,
            'provider' => 'MetaTrader 5',
            'status' => 'active'
        ],
        [
            'account_type' => 'Demo',
            'account_number' => 'DMO-' . str_pad($clientId, 6, '0', STR_PAD_LEFT) . '-003',
            'currency' => 'USD',
            'balance' => 100000.00,
            'provider' => 'cTrader',
            'status' => 'active'
        ]
    ];
    
    $accountStmt = $pdo->prepare("
        INSERT INTO client_accounts (client_id, account_type, account_number, currency, balance, provider, status, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ");
    
    $accountIds = [];
    foreach ($accounts as $account) {
        $accountStmt->execute([
            $clientId,
            $account['account_type'],
            $account['account_number'],
            $account['currency'],
            $account['balance'],
            $account['provider'],
            $account['status']
        ]);
        $accountIds[] = $pdo->lastInsertId();
        echo "Cuenta creada: {$account['account_number']} - {$account['balance']} {$account['currency']}\n";
    }
    
    // 4. Crear depósitos de ejemplo
    $deposits = [
        ['amount' => 5000.00, 'currency' => 'USD', 'method' => 'Transferencia Bancaria', 'reference' => 'TXN-001', 'status' => 'confirmed'],
        ['amount' => 2500.00, 'currency' => 'USD', 'method' => 'Tarjeta de Crédito', 'reference' => 'TXN-002', 'status' => 'confirmed'],
        ['amount' => 3000.00, 'currency' => 'EUR', 'method' => 'Skrill', 'reference' => 'TXN-003', 'status' => 'confirmed'],
        ['amount' => 1500.00, 'currency' => 'USD', 'method' => 'PayPal', 'reference' => 'TXN-004', 'status' => 'pending']
    ];
    
    $depositStmt = $pdo->prepare("
        INSERT INTO client_deposits (client_id, amount, currency, method, reference, status, created_at)
        VALUES (?, ?, ?, ?, ?, ?, DATE_SUB(NOW(), INTERVAL FLOOR(RAND() * 30) DAY))
    ");
    
    foreach ($deposits as $deposit) {
        $depositStmt->execute([
            $clientId,
            $deposit['amount'],
            $deposit['currency'],
            $deposit['method'],
            $deposit['reference'],
            $deposit['status']
        ]);
        echo "Depósito creado: {$deposit['amount']} {$deposit['currency']} - {$deposit['method']}\n";
    }
    
    // 5. Crear transacciones de ejemplo
    $transactions = [
        ['type' => 'deposit', 'amount' => 5000.00, 'currency' => 'USD', 'reference' => 'DEP-001', 'notes' => 'Depósito inicial'],
        ['type' => 'deposit', 'amount' => 2500.00, 'currency' => 'USD', 'reference' => 'DEP-002', 'notes' => 'Segundo depósito'],
        ['type' => 'withdrawal', 'amount' => -750.00, 'currency' => 'USD', 'reference' => 'WTH-001', 'notes' => 'Retiro parcial'],
        ['type' => 'adjustment', 'amount' => 1000.50, 'currency' => 'USD', 'reference' => 'ADJ-001', 'notes' => 'Ajuste por ganancia'],
        ['type' => 'deposit', 'amount' => 3000.00, 'currency' => 'EUR', 'reference' => 'DEP-003', 'notes' => 'Depósito en EUR'],
        ['type' => 'adjustment', 'amount' => -79.25, 'currency' => 'EUR', 'reference' => 'ADJ-002', 'notes' => 'Comisión de trading']
    ];
    
    $transactionStmt = $pdo->prepare("
        INSERT INTO client_transactions (client_id, type, amount, currency, reference, notes, created_at)
        VALUES (?, ?, ?, ?, ?, ?, DATE_SUB(NOW(), INTERVAL FLOOR(RAND() * 60) DAY))
    ");
    
    foreach ($transactions as $transaction) {
        $transactionStmt->execute([
            $clientId,
            $transaction['type'],
            $transaction['amount'],
            $transaction['currency'],
            $transaction['reference'],
            $transaction['notes']
        ]);
        echo "Transacción creada: {$transaction['type']} {$transaction['amount']} {$transaction['currency']}\n";
    }
    
    // Confirmar transacción
    $pdo->commit();
    
    echo "\n✅ Cliente de ejemplo creado exitosamente!\n";
    echo "📧 Email: {$clientData['email']}\n";
    echo "🔑 Password: demo123\n";
    echo "🆔 Client ID: $clientId\n";
    echo "\nPuedes usar estas credenciales para acceder al dashboard del cliente.\n";
    echo "URL: http://127.0.0.1:8080/modules/client_portal/login.php\n";
    
} catch (Exception $e) {
    // Revertir transacción en caso de error
    if ($pdo->inTransaction()) {
        $pdo->rollback();
    }
    
    echo "❌ Error al crear el cliente: " . $e->getMessage() . "\n";
    echo "Trace: " . $e->getTraceAsString() . "\n";
}
?>