<?php
// db.php - Central Database Connection for "mehok"
//
// Real connection credentials are NOT stored in this file. They live in
// config.local.php, which is not part of the deployment package and is
// never shared with anyone (including the developer/AI) — you create it
// once, directly on the server, from config.local.php.example.

$configFile = __DIR__ . '/config.local.php';

if (!file_exists($configFile)) {
    error_log('db.php: missing config.local.php - copy config.local.php.example to config.local.php and fill in real credentials.');
    http_response_code(503);
    die('The system is temporarily unavailable. Please try again shortly, or contact support if this persists.');
}

require $configFile;
// config.local.php must define: $host, $dbname, $username, $password

$charset = 'utf8mb4';
$dsn     = "mysql:host=$host;dbname=$dbname;charset=$charset";

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, // Throws clear errors if a query fails
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,       // Fetches data as clean associative arrays
    PDO::ATTR_EMULATE_PREPARES   => false,                  // Uses native SQL prepared statements
];

/**
 * Returns the first argument that is non-null AND non-empty (after
 * trimming strings), or null if every argument is null/empty.
 *
 * Plain PHP `??` only skips a NULL value — it does NOT skip an empty
 * string ''. Several tables in this schema store the "same" real-world
 * value in two places (e.g. tbl_appliance_inspections.ItemName vs.
 * tbl_jobs.Item_Name); once a form saves the more specific column as ''
 * (an inspector clears a field and saves), a `??` fallback chain silently
 * stops there instead of falling back to the other, still-good value.
 * Use this helper anywhere a value needs to fall back across more than
 * one column/source.
 */
function firstNonEmpty(...$values)
{
    foreach ($values as $v) {
        $v = is_string($v) ? trim($v) : $v;
        if ($v !== null && $v !== '') {
            return $v;
        }
    }
    return null;
}

try {
    $pdo = new PDO($dsn, $username, $password, $options);
    // Connection successful!
} catch (\PDOException $e) {
    // SECURITY FIX: never leak raw connection details to a visitor if the
    // DB is down — the real error goes to the server's error log instead.
                        error_log('Database connection failed: ' . $e->getMessage());
                            http_response_code(503);
                               die('The system is temporarily unavailable. Please try again shortly, or contact support if this persists.');
}
