<?php
/**
 * Safe Database Connection Helper
 * This file provides a safe way to connect to the database without causing redirect loops
 */

function getSafeDbConnection() {
    static $connection = null;
    
    if ($connection !== null) {
        return $connection;
    }
    
    // Check if config file exists
    $config_file = '';
    if (file_exists('config.php')) {
        $config_file = 'config.php';
    } else {
        return false;
    }
    
    include $config_file;
    
    try {
        // Check if constants are defined
        if (!defined('MYSQL_HOST') && !defined('DB_HOST')) {
            return false;
        }
        
        // Use the appropriate constants based on which file was loaded
        $host = defined('DB_HOST') ? constant('DB_HOST') : constant('MYSQL_HOST');
        $database = defined('DB_NAME') ? constant('DB_NAME') : constant('MYSQL_DATABASE');
        $user = defined('DB_USER') ? constant('DB_USER') : constant('MYSQL_USER');
        $password = defined('DB_PASS') ? constant('DB_PASS') : constant('MYSQL_PASSWORD');
        
        $connection = new PDO(
            "mysql:host=" . $host . ";dbname=" . $database,
            $user,
            $password
        );
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        return $connection;
        
    } catch (Exception $e) {
        return false;
    }
}

function isInstalled() {
    $conn = getSafeDbConnection();
    if (!$conn) {
        return false;
    }
    
    try {
        // Check if system_user table exists (created by InstallController)
        $stmt = $conn->prepare("SHOW TABLES LIKE 'system_user'");
        $stmt->execute();
        return ($stmt->rowCount() > 0);
    } catch (Exception $e) {
        return false;
    }
}

function hasSubscriptionTables() {
    $conn = getSafeDbConnection();
    if (!$conn) {
        return false;
    }
    
    try {
        $stmt = $conn->prepare("SHOW TABLES LIKE 'subscription_plans'");
        $stmt->execute();
        return ($stmt->rowCount() > 0);
    } catch (Exception $e) {
        return false;
    }
}

function configExists() {
    return file_exists('config.php');
}
