<?php
// db_improved.php: Improved database connection for Ton Sui Mining Auth
// Database connection with improved error handling and environment variable support

// Add CORS // Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';
 
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Set up error logging
ini_set('display_errors', 0); // Don't display errors to browser
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/db_error.log');

// Debug function to log connection attempts
function logDbConnectionAttempt($message, $isError = false) {
    $timestamp = date('Y-m-d H:i:s');
    $prefix = $isError ? "ERROR" : "INFO";
    error_log("[$timestamp] [$prefix] $message");
}

// Try to load configuration
try {
    logDbConnectionAttempt("Loading config file");
    
    // First, try to load from the auth-backend directory
    $configFile = __DIR__ . '/config.php';
    if (file_exists($configFile)) {
        $config = require $configFile;
        logDbConnectionAttempt("Loaded config from auth-backend directory");
    }
    // If not found, try to load from the project root
    else {
        $rootConfigFile = dirname(__DIR__) . '/config.php';
        if (file_exists($rootConfigFile)) {
            $config = require $rootConfigFile;
            logDbConnectionAttempt("Loaded config from project root directory");
        } else {
            throw new Exception("Configuration file not found in auth-backend or project root");
        }
    }
    
    // Extract database credentials from config
    $DB_HOST = $config['db_host'] ?? 'localhost';
    $DB_NAME = $config['db_name'] ?? '';
    $DB_USER = $config['db_user'] ?? '';
    $DB_PASS = $config['db_pass'] ?? '';
    $DB_PORT = $config['db_port'] ?? '3306';
    
    logDbConnectionAttempt("Config loaded. Host: $DB_HOST, DB: $DB_NAME, User: $DB_USER, Port: $DB_PORT");
    
    // Validate required config
    if (empty($DB_NAME) || empty($DB_USER)) {
        throw new Exception("Database configuration is incomplete. Missing database name or username.");
    }
    
    // Create PDO connection with port specification
    $dsn = "mysql:host=$DB_HOST;port=$DB_PORT;dbname=$DB_NAME;charset=utf8mb4";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];
    
    logDbConnectionAttempt("Attempting to connect to database: $DB_HOST:$DB_PORT / $DB_NAME");
    $pdo = new PDO($dsn, $DB_USER, $DB_PASS, $options);
    logDbConnectionAttempt("Successfully connected to database");

} catch (PDOException $e) {
    logDbConnectionAttempt("Database connection failed: " . $e->getMessage(), true);
    // Don't expose error details in production, just log them
    http_response_code(500);
    header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
    echo json_encode(['success' => false, 'message' => 'Database connection error']);
    exit;
} catch (Exception $e) {
    logDbConnectionAttempt("Configuration error: " . $e->getMessage(), true);
    http_response_code(500);
    header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
    echo json_encode(['success' => false, 'message' => 'Database configuration error']);
    exit;
}
