<?php
if (!isset($_SESSION)) session_start();
require_once __DIR__ . '/../config.php';

// Output escaping
function e($str) { return htmlspecialchars((string)$str, ENT_QUOTES, 'UTF-8'); }

// Load a JSON file from /data/ — returns array or object
function getData($name) {
    $path = DATA_PATH . '/' . $name . '.json';
    if (!file_exists($path)) return [];
    return json_decode(file_get_contents($path), true) ?? [];
}

// Save array to /data/name.json
function saveData($name, $data) {
    file_put_contents(DATA_PATH . '/' . $name . '.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// Get settings — always returns flat array
function getSettings() { return getData('settings'); }

// Generate next numeric ID for leads/exhibitors/etc
function generateId($items) {
    if (empty($items)) return 1;
    return max(array_column($items, 'id')) + 1;
}

// Truncate text to n chars
function truncateText($text, $n = 100) {
    return strlen($text) > $n ? substr($text, 0, $n) . '...' : $text;
}

// Slug generator
function slugify($text) {
    return strtolower(trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($text)), '-'));
}

// Flash messages (session-based)
function setFlash($type, $msg) { $_SESSION['flash'] = ['type' => $type, 'msg' => $msg]; }
function getFlash() {
    if (!isset($_SESSION['flash'])) return null;
    $f = $_SESSION['flash']; unset($_SESSION['flash']); return $f;
}

// Redirect
function redirect($url) { header('Location: ' . $url); exit; }

// Send email using PHPMailer
function sendEmail($to, $subject, $htmlBody) {
    require_once VENDOR_PATH . '/Exception.php';
    require_once VENDOR_PATH . '/PHPMailer.php';
    require_once VENDOR_PATH . '/SMTP.php';
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = SMTP_ENCRYPTION;
        $mail->Port       = SMTP_PORT;
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;
        $mail->send();
    } catch (Exception $e) { /* Silent fail */ }
}
