<?php
/**
 * Database Configuration
 */

// Database credentials
define('DB_HOST', '127.0.0.1'); // Using IP instead of 'localhost'
define('DB_PORT', '3306');      // Specify MySQL port explicitly
define('DB_NAME', 'baso_alam_db'); // Updated database name
define('DB_USER', 'root');      // Change this to your database username
define('DB_PASS', '');          // Change this to your database password

// Create connection
function getDbConnection() {
    try {
        $conn = new PDO(
            "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4",
            DB_USER,
            DB_PASS,
            array(
                PDO::ATTR_TIMEOUT => 5, // 5 seconds timeout
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            )
        );
        return $conn;
    } catch(PDOException $e) {
        // Log error instead of displaying it in production
        error_log("Database connection failed: " . $e->getMessage());
        error_log("Connection details - Host: " . DB_HOST . ", Port: " . DB_PORT . ", Database: " . DB_NAME . ", User: " . DB_USER);
        return null;
    }
}

// Function to check if database connection is successful
function testDatabaseConnection() {
    $conn = getDbConnection();
    if ($conn) {
        try {
            // Test the connection with a simple query
            $stmt = $conn->query("SELECT 1");
            $result = $stmt->fetch();
            return true;
        } catch (PDOException $e) {
            error_log("Database connection test failed: " . $e->getMessage());
            return false;
        }
    }
    return false;
}

// Function to handle database errors gracefully in the UI
function showDatabaseError($e, $customMessage = "Terjadi kesalahan dalam koneksi database") {
    if (defined('DEBUG_MODE') && DEBUG_MODE) {
        echo "<div class='bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-4'>";
        echo "<p><strong>Error:</strong> " . $customMessage . "</p>";
        echo "<p>" . $e->getMessage() . "</p>";
        echo "</div>";
    } else {
        echo "<div class='bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-4'>";
        echo "<p><strong>Error:</strong> " . $customMessage . "</p>";
        echo "<p>Silakan coba lagi nanti atau hubungi administrator.</p>";
        echo "</div>";
    }
}

// Function to get database connection status for debugging
function getDatabaseStatus() {
    $status = array();
    
    // Test basic connection
    $conn = getDbConnection();
    if ($conn) {
        $status['connection'] = 'success';
        
        // Test if database exists and has required tables
        try {
            $tables = array('users', 'products', 'orders', 'order_items', 'transactions', 'payment_proofs');
            $existing_tables = array();
            
            foreach ($tables as $table) {
                $stmt = $conn->query("SHOW TABLES LIKE '$table'");
                if ($stmt->rowCount() > 0) {
                    $existing_tables[] = $table;
                }
            }
            
            $status['tables'] = $existing_tables;
            $status['missing_tables'] = array_diff($tables, $existing_tables);
            
        } catch (PDOException $e) {
            $status['tables_error'] = $e->getMessage();
        }
        
    } else {
        $status['connection'] = 'failed';
        $status['error'] = 'Could not establish database connection';
    }
    
    return $status;
} 