<?php
// Evita ejecutar el bootstrap más de una vez
if (!defined('APP_BOOTSTRAPPED')) {
    define('APP_BOOTSTRAPPED', true);

    // Sesión
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    // Conexión PDO (declara la clase sólo si no existe)
    if (!class_exists('Database')) {
        class Database {
            private $host = "localhost";
            private $db   = "farmacia";
            private $user = "root";
            private $pass = "";
            private $charset = "utf8mb4";
            public  $pdo;

            public function __construct() {
                $dsn = "mysql:host={$this->host};dbname={$this->db};charset={$this->charset}";
                $options = [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                ];
                $this->pdo = new PDO($dsn, $this->user, $this->pass, $options);
            }
        }
    }

    // Crea $pdo sólo si aún no existe
    if (!isset($pdo) || !($pdo instanceof PDO)) {
        $__db = new Database();
        $pdo = $__db->pdo;
    }

    // Helpers seguros: sólo si no existen
    if (!function_exists('h')) {
        function h($str){ return htmlspecialchars((string)$str, ENT_QUOTES, 'UTF-8'); }
    }
    if (!function_exists('today')) {
        function today(){ return (new DateTime('now', new DateTimeZone('America/Santiago')))->format('Y-m-d'); }
    }
    if (!function_exists('add_days')) {
        function add_days($date, $days=40){ $d = new DateTime($date); $d->modify("+$days days"); return $d->format('Y-m-d'); }
    }
    if (!function_exists('fmt_date')) {
        function fmt_date($iso){ if(!$iso) return ''; $d = DateTime::createFromFormat('Y-m-d', substr($iso,0,10)); return $d? $d->format('d-m-Y') : $iso; }
    }
}
