<?php
require_once __DIR__ . '/../../config/init.php';

try {
    $db = getDB();
    $db->exec('BEGIN TRANSACTION');

    // Create cash_fund table
    $db->exec("CREATE TABLE IF NOT EXISTS cash_fund (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        initial_balance DECIMAL(10,2) NOT NULL,
        current_balance DECIMAL(10,2) NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // Create bank_account table
    $db->exec("CREATE TABLE IF NOT EXISTS bank_account (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        account_number VARCHAR(50) NOT NULL,
        bank_name VARCHAR(100) NOT NULL,
        initial_balance DECIMAL(10,2) NOT NULL,
        current_balance DECIMAL(10,2) NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // Create financial_transactions table
    $db->exec("CREATE TABLE IF NOT EXISTS financial_transactions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        transaction_type VARCHAR(50) NOT NULL,
        amount DECIMAL(10,2) NOT NULL,
        source_type VARCHAR(50) NOT NULL,
        source_id INTEGER,
        destination_type VARCHAR(50),
        destination_id INTEGER,
        description TEXT,
        reference_type VARCHAR(50),
        reference_id INTEGER,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    $db->exec('COMMIT');
    echo "Financial accounts tables created successfully!\n";

} catch (Exception $e) {
    $db->exec('ROLLBACK');
    echo "Error creating tables: " . $e->getMessage() . "\n";
    exit(1);
}
