<?php
// db_fixed.php: Fixed 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");
}

// Hard-coded database credentials for testing
// Remove these after confirming connection works and replace with config-based approach
$DB_HOST = "localhost"; // Change to your actual host
$DB_NAME = "tonsui"; // Change to your actual database name
$DB_USER = "tonsui_user"; // Change to your actual username
$DB_PASS = "password"; // Change to your actual password

try {
    // Create PDO connection
    $dsn = "mysql:host=$DB_HOST;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_NAME");
    $pdo = new PDO($dsn, $DB_USER, $DB_PASS, $options);
    logDbConnectionAttempt("Successfully connected to database");

} catch (PDOException $e) {
    logDbConnectionAttempt("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;
}
