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

try {
    // Check if previous_balances table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'previous_balances'");
    $exists = $stmt->fetch();
    
    if ($exists) {
        echo "✅ Table 'previous_balances' exists<br>";
        
        // Check table structure
        $stmt = $pdo->query("DESCRIBE previous_balances");
        $columns = $stmt->fetchAll();
        echo "<h4>Table Structure:</h4><ul>";
        foreach ($columns as $col) {
            echo "<li>{$col['Field']} - {$col['Type']}</li>";
        }
        echo "</ul>";
        
        // Check some records
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM previous_balances");
        $count = $stmt->fetch();
        echo "Records in table: {$count['count']}<br>";
    } else {
        echo "❌ Table 'previous_balances' does not exist<br>";
        echo "Need to run the table creation script<br>";
        
        // Attempt to create the table
        $sql = "
        CREATE TABLE IF NOT EXISTS previous_balances (
            id INT AUTO_INCREMENT PRIMARY KEY,
            account_name VARCHAR(100) NOT NULL,
            account_type ENUM('cash', 'bank', 'mobile', 'other') DEFAULT 'cash',
            balance_date DATE NOT NULL,
            opening_balance DECIMAL(15,2) NOT NULL DEFAULT 0.00,
            description TEXT,
            created_by INT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            
            INDEX idx_account_name (account_name),
            INDEX idx_balance_date (balance_date),
            INDEX idx_account_type (account_type),
            FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
        )";
        
        $pdo->exec($sql);
        echo "✅ Attempted to create the table<br>";
    }
    
    echo "<br>✅ Database check completed successfully!";
    
} catch (Exception $e) {
    echo "❌ Database error: " . $e->getMessage();
}
?>