<?php
require_once __DIR__ . '/vendor/autoload.php';

use App\Models\Bank;
use App\Models\ChartOfAccount;
use App\Services\BankAccountService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

// Initialize Laravel application
$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();

try {
    // Create a test bank with a unique name
    $testBankName = 'Test Bank ' . date('YmdHis');
    $companyId = 3; // Assuming company ID 3 exists, adjust if needed

    echo "Creating a test bank: $testBankName\n";

    // Begin transaction
    DB::beginTransaction();

    try {
        // Create a new bank
        $bank = new Bank();
        $bank->name = $testBankName;
        $bank->company_id = $companyId;
        $bank->is_active = true;
        $bank->save();

        echo "Successfully created bank with ID: {$bank->id}\n";

        // Create a new instance of BankAccountService
        $bankAccountService = new BankAccountService();

        // Try to create a bank account
        echo "Attempting to create a bank account...\n";

        // Check for existing accounts with similar codes
        $cashAndBanksAccount = ChartOfAccount::where('company_id', $companyId)
            ->where('account_code', '1110')
            ->where('name', 'النقدية والبنوك')
            ->first();

        if ($cashAndBanksAccount) {
            echo "Found Cash and Banks account with ID: {$cashAndBanksAccount->id}\n";

            // Check for existing bank accounts
            $existingBankAccounts = ChartOfAccount::where('parent_id', $cashAndBanksAccount->id)
                ->where('is_bank_account', true)
                ->where('company_id', $companyId)
                ->orderBy('account_code', 'desc')
                ->get();

            echo "Existing bank accounts under Cash and Banks:\n";
            foreach ($existingBankAccounts as $existingAccount) {
                echo "- ID: {$existingAccount->id}, Code: {$existingAccount->account_code}, Name: {$existingAccount->name}\n";
            }
        } else {
            echo "Cash and Banks account not found for company ID: $companyId\n";
        }

        // Now try to create the bank account
        $account = $bankAccountService->createBankAccount($bank);

        if ($account) {
            echo "Successfully created bank account:\n";
            echo "ID: {$account->id}\n";
            echo "Account Code: {$account->account_code}\n";
            echo "Name: {$account->name}\n";
            echo "Is Parent: " . ($account->is_parent ? 'Yes' : 'No') . "\n";
            echo "Parent ID: " . ($account->parent_id ?? 'None') . "\n";
        } else {
            echo "Failed to create bank account. No exception was thrown, but no account was returned.\n";
        }

        // Rollback transaction to avoid creating test data
        DB::rollBack();
        echo "\nTransaction rolled back to avoid creating test data.\n";
    } catch (\Exception $e) {
        // Rollback transaction
        DB::rollBack();

        echo "Error during test: " . $e->getMessage() . "\n";
        echo "File: " . $e->getFile() . "\n";
        echo "Line: " . $e->getLine() . "\n";
        echo "Trace:\n" . $e->getTraceAsString() . "\n";
    }

    // Now let's check the BankController store method logic
    echo "\nSimulating BankController store method logic...\n";

    // Create a test bank with a unique name
    $testBankName = 'Test Bank Controller ' . date('YmdHis');

    try {
        // Begin transaction
        DB::beginTransaction();

        // Create a new bank
        $bank = new Bank();
        $bank->name = $testBankName;
        $bank->company_id = $companyId;
        $bank->is_active = true;
        $bank->save();

        echo "Successfully created bank with ID: {$bank->id}\n";

        // Create a new instance of BankAccountService
        $bankAccountService = new BankAccountService();

        // Create bank account
        $account = $bankAccountService->createBankAccount($bank);

        if (!$account) {
            throw new \Exception('فشل في إنشاء حساب البنك في شجرة الحسابات');
        }

        echo "Successfully created bank account with ID: {$account->id}\n";

        // Rollback transaction to avoid creating test data
        DB::rollBack();
        echo "Transaction rolled back to avoid creating test data.\n";
    } catch (\Exception $e) {
        // Rollback transaction
        DB::rollBack();

        echo "Error in controller simulation: " . $e->getMessage() . "\n";
        echo "File: " . $e->getFile() . "\n";
        echo "Line: " . $e->getLine() . "\n";
    }
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n";
}
