<?php

/**
 * Database Helper - Handles missing tables gracefully
 */
class DatabaseHelper 
{
    /**
     * Check if a table exists
     */
    public static function tableExists(string $tableName): bool 
    {
        try {
            $pdo = getPDO();
            $stmt = $pdo->query("SELECT 1 FROM `$tableName` LIMIT 1");
            return true;
        } catch (PDOException $e) {
            return false;
        }
    }
    
    /**
     * Safe query execution with table existence check
     */
    public static function safeQuery(string $query, array $params = []): array 
    {
        $pdo = getPDO();
        try {
            $stmt = $pdo->prepare($query);
            $stmt->execute($params);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            // Table doesn't exist or other error, return empty array
            return [];
        }
    }
    
    /**
     * Safe count query with table existence check
     */
    public static function safeCount(string $tableName, string $whereClause = '', array $params = []): int 
    {
        if (!self::tableExists($tableName)) {
            return 0;
        }
        
        try {
            $pdo = getPDO();
            $query = "SELECT COUNT(*) as count FROM `$tableName`";
            if ($whereClause) {
                $query .= " WHERE $whereClause";
            }
            $stmt = $pdo->prepare($query);
            $stmt->execute($params);
            return $stmt->fetch()['count'] ?? 0;
        } catch (PDOException $e) {
            return 0;
        }
    }
    
    /**
     * Get default invoice settings
     */
    public static function getDefaultInvoiceSettings(): array 
    {
        return [
            'currency' => 'USD',
            'currency_symbol' => '$',
            'company_name' => 'Default Company',
            'company_address' => '',
            'company_phone' => '',
            'company_email' => '',
            'tax_rate' => 0,
            'payment_terms' => 'Net 30',
            'notes' => ''
        ];
    }
    
    /**
     * List all missing tables
     */
    public static function getMissingTables(): array 
    {
        $expectedTables = [
            'companies', 'users', 'user_sessions', 'clients', 'proposals', 'contracts', 'invoices',
            'invoice_items', 'subscription_plans', 'subscriptions', 'usage_tracking', 'payment_methods',
            'billing_invoices', 'templates', 'modules', 'invoice_payments', 'invoice_settings',
            'contract_templates', 'tax_brackets', 'labels'
        ];
        
        $missing = [];
        foreach ($expectedTables as $table) {
            if (!self::tableExists($table)) {
                $missing[] = $table;
            }
        }
        
        return $missing;
    }
    
    /**
     * Check if core functionality is available
     */
    public static function isCoreFunctional(): bool 
    {
        $requiredTables = ['companies', 'users', 'clients', 'proposals', 'contracts', 'invoices'];
        
        foreach ($requiredTables as $table) {
            if (!self::tableExists($table)) {
                return false;
            }
        }
        
        return true;
    }
}
