<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once __DIR__ . '/config.php'; // BASE_URL, DB_* constantes

// Caminhos
if (!defined('APP_ROOT')) {
    define('APP_ROOT', dirname(__DIR__, 2)); // .../gabinete
}

// Raiz pública (usa /public se existir)
if (!function_exists('public_root')) {
    function public_root(): string {
        $root = APP_ROOT;
        return is_dir($root . '/public') ? ($root . '/public') : $root;
    }
}

// Escape HTML
if (!function_exists('e')) {
    function e(?string $v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

// URL da foto do colaborador (ou placeholder)
if (!function_exists('employeePhotoUrl')) {
    function employeePhotoUrl(?string $photoPath): string {
        $placeholder = BASE_URL . '/assets/img/placeholder-user.png';
        if (!$photoPath) return $placeholder;
        $fs = public_root() . '/' . ltrim($photoPath, '/');
        return is_file($fs) ? BASE_URL . '/' . ltrim($photoPath, '/') : $placeholder;
    }
}

// Conexão PDO (global $pdo)
if (!isset($pdo) || !($pdo instanceof PDO)) {
    $host   = defined('DB_HOST')   ? DB_HOST   : '127.0.0.1';
    $db     = defined('DB_NAME')   ? DB_NAME   : '';
    $user   = defined('DB_USER')   ? DB_USER   : 'root';
    $pass   = defined('DB_PASS')   ? DB_PASS   : '';
    $port   = defined('DB_PORT')   ? (int)DB_PORT : 3306;
    $socket = defined('DB_SOCKET') ? DB_SOCKET : null;

    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    $lastEx = null;
    $dsnTried = [];

    try {
        if (!empty($socket)) {
            $dsn = "mysql:unix_socket={$socket};dbname={$db};charset=utf8mb4";
            $dsnTried[] = $dsn;
            $pdo = new PDO($dsn, $user, $pass, $options);
        } else {
            $dsn = "mysql:host={$host};port={$port};dbname={$db};charset=utf8mb4";
            $dsnTried[] = $dsn;
            $pdo = new PDO($dsn, $user, $pass, $options);
        }
    } catch (PDOException $e) {
        $lastEx = $e;
        foreach ([
            '/var/run/mysqld/mysqld.sock',
            '/tmp/mysql.sock',
            '/Applications/MAMP/tmp/mysql/mysql.sock',
            'C:/xampp/mysql/mysql.sock',
        ] as $sock) {
            try {
                $dsn = "mysql:unix_socket={$sock};dbname={$db};charset=utf8mb4";
                $dsnTried[] = $dsn;
                $pdo = new PDO($dsn, $user, $pass, $options);
                $lastEx = null;
                break;
            } catch (PDOException $e2) {
                $lastEx = $e2;
            }
        }
        if ($lastEx) {
            $msg  = "Erro de conexão ao MySQL.\n";
            $msg .= "Tentativas:\n - " . implode("\n - ", $dsnTried) . "\n";
            $msg .= "Detalhes: " . $lastEx->getMessage();
            die(nl2br(e($msg)));
        }
    }
}
// EOF
