<?php
require_once 'config/database.php';

echo "<h2>Testing Previous Balance Functionality</h2>";

try {
    // Check if previous_balances table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'previous_balances'");
    $exists = $stmt->fetch();
    
    if (!$exists) {
        echo "<p style='color: red;'>❌ Previous balances table does not exist!</p>";
        exit;
    } else {
        echo "<p style='color: green;'>✅ Previous balances table exists</p>";
    }
    
    // Test inserting a new previous balance
    echo "<h3>Testing Insert Operation</h3>";
    $stmt = $pdo->prepare("INSERT INTO previous_balances (account_name, account_type, balance_date, opening_balance, description, created_by) VALUES (?, ?, ?, ?, ?, ?)");
    $result = $stmt->execute(['Test Account', 'cash', date('Y-m-d'), 10000.00, 'Test entry for verification', 1]);
    
    if ($result) {
        echo "<p style='color: green;'>✅ Successfully inserted test record</p>";
    } else {
        echo "<p style='color: red;'>❌ Failed to insert test record</p>";
    }
    
    // Test selecting records
    echo "<h3>Testing Select Operation</h3>";
    $stmt = $pdo->query("SELECT * FROM previous_balances ORDER BY id DESC LIMIT 5");
    $records = $stmt->fetchAll();
    
    if (!empty($records)) {
        echo "<p style='color: green;'>✅ Successfully retrieved " . count($records) . " records</p>";
        
        echo "<h4>Latest Records:</h4>";
        echo "<table border='1' cellpadding='5'>";
        echo "<tr><th>ID</th><th>Account Name</th><th>Type</th><th>Balance Date</th><th>Opening Balance</th><th>Description</th></tr>";
        foreach ($records as $record) {
            echo "<tr>";
            echo "<td>" . $record['id'] . "</td>";
            echo "<td>" . htmlspecialchars($record['account_name']) . "</td>";
            echo "<td>" . $record['account_type'] . "</td>";
            echo "<td>" . $record['balance_date'] . "</td>";
            echo "<td>৳" . number_format($record['opening_balance'], 2) . "</td>";
            echo "<td>" . htmlspecialchars($record['description']) . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p style='color: orange;'>⚠️ No records found in previous_balances table</p>";
    }
    
    // Test updating a record
    echo "<h3>Testing Update Operation</h3>";
    if (!empty($records)) {
        $first_record = $records[0];
        $stmt = $pdo->prepare("UPDATE previous_balances SET opening_balance = ? WHERE id = ?");
        $result = $stmt->execute([15000.00, $first_record['id']]);
        
        if ($result) {
            echo "<p style='color: green;'>✅ Successfully updated record ID: " . $first_record['id'] . "</p>";
        } else {
            echo "<p style='color: red;'>❌ Failed to update record</p>";
        }
    }
    
    // Test calculating total balances
    echo "<h3>Testing Total Calculation</h3>";
    $stmt = $pdo->query("SELECT SUM(opening_balance) as total_balance, COUNT(*) as record_count FROM previous_balances");
    $totals = $stmt->fetch();
    
    echo "<p>Total Balance: ৳" . number_format($totals['total_balance'], 2) . "</p>";
    echo "<p>Total Records: " . $totals['record_count'] . "</p>";
    
    // Test integration with income/expense report logic
    echo "<h3>Testing Integration with Reports</h3>";
    $end_date = date('Y-m-d');
    $prevBalanceSql = "SELECT SUM(opening_balance) as total_prev_balance FROM previous_balances WHERE balance_date <= ?";
    $prevBalanceStmt = $pdo->prepare($prevBalanceSql);
    $prevBalanceStmt->execute([$end_date]);
    $prevBalanceData = $prevBalanceStmt->fetch();
    
    $previousBalance = $prevBalanceData['total_prev_balance'] ?? 0;
    echo "<p>Previous Balance for date range: ৳" . number_format($previousBalance, 2) . "</p>";
    
    // Test that the previous balance page exists
    if (file_exists('previous_balance.php')) {
        echo "<p style='color: green;'>✅ Previous Balance management page exists</p>";
    } else {
        echo "<p style='color: red;'>❌ Previous Balance management page does not exist</p>";
    }
    
    echo "<h3>Testing Completed Successfully! 🎉</h3>";
    echo "<p>The Previous Balance functionality has been implemented and tested successfully.</p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Error: " . $e->getMessage() . "</p>";
}
?>