<?php
// Time zone
date_default_timezone_set('Asia/Kolkata');

// Database configuration
// You can override these by setting environment variables or by creating a local config
$db_host = getenv('DB_HOST') ?: (isset($_SERVER['DB_HOST']) ? $_SERVER['DB_HOST'] : 'localhost');
$db_user = getenv('DB_USER') ?: (isset($_SERVER['DB_USER']) ? $_SERVER['DB_USER'] : 'root');
$db_pass = getenv('DB_PASS') ?: (isset($_SERVER['DB_PASS']) ? $_SERVER['DB_PASS'] : '');
$db_name = getenv('DB_NAME') ?: (isset($_SERVER['DB_NAME']) ? $_SERVER['DB_NAME'] : 'inba_rice');

// Production server configuration (override defaults with your server credentials)
$db_host = 'localhost';
$db_user = 'root';  
$db_pass = '';
$db_name = 'inba_rice';

// MySQLi connection (existing usage)
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (mysqli_connect_errno()) {
    error_log("MySQLi Connection Failed: " . mysqli_connect_error());
    error_log("Connection attempted with Host: $db_host, User: $db_user, Database: $db_name");
    // If called from an API endpoint, return JSON instead of HTML/text to avoid corrupting responses
    if (stripos($_SERVER['SCRIPT_NAME'] ?? '', 'api/') !== false) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
        exit();
    }
    die("Database connection failed");
}

// PDO connection (needed for newer POS detailed endpoints)
if (!isset($dbh)) {
    try {
        $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
        $dbh = new PDO($dsn, $db_user, $db_pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
    } catch (PDOException $e) {
        error_log('PDO Connection Failed: ' . $e->getMessage());
        error_log("Connection attempted with Host: $db_host, User: $db_user, Database: $db_name");
        // Fallback: expose a simple JSON error if this script expected JSON
        if (stripos($_SERVER['SCRIPT_NAME'], 'api/') !== false) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Database (PDO) connection failed']);
            exit();
        }
    }
}
?>
