<?php
require_once __DIR__ . '/api/vendor/autoload.php';
require_once __DIR__ . '/api/config/database.php';
require_once __DIR__ . '/api/helpers/Response.php';
require_once __DIR__ . '/api/helpers/Validator.php';
require_once __DIR__ . '/api/helpers/UUID.php';
require_once __DIR__ . '/api/helpers/AuditLogger.php';
require_once __DIR__ . '/api/services/AccountingService.php';
require_once __DIR__ . '/api/controllers/ExpenseController.php';

try {
    $db = Database::connect();
    
    // mock user
    $user = (object)['id' => 1];
    $ctrl = new ExpenseController($db, $user);
    
    // find a bank_cash account id
    $stmt = $db->query("SELECT id FROM accounts WHERE type = 'bank_cash' LIMIT 1");
    $accountId = $stmt->fetchColumn();
    
    // find an item id
    $stmt = $db->query("SELECT id FROM items LIMIT 1");
    $itemId = $stmt->fetchColumn();

    if ($accountId && $itemId) {
        echo "Testing Expense Creation with Item ID: $itemId and Account ID: $accountId\n";
        
        $data = [
            'date' => date('Y-m-d'),
            'narration' => 'Test Expense for Item',
            'amount' => 500,
            'account_id' => $accountId,
            'item_id' => $itemId
        ];

        ob_start();
        $ctrl->store($data);
        $json = ob_get_clean();
        
        echo "\nResponse:\n";
        echo $json;
        
        // Let's verify the journal entry
        $stmt = $db->prepare("SELECT * FROM journals WHERE source_type = 'expense' ORDER BY id DESC LIMIT 1");
        $stmt->execute();
        $journal = $stmt->fetch();
        echo "\nJournal Record:\n";
        print_r($journal);
    } else {
        echo "Missing required data to test expense creation.\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
