<?php
// Database configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'cms_db');

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die("DB Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8mb4");

// Base URL - adjust to your installation path
define('BASE_URL', '/tycon/cms');
define('UPLOAD_DIR', __DIR__ . '/uploads');
define('UPLOAD_URL', BASE_URL . '/uploads');

session_start();

// Helpers
function e($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }

function redirect($url) { header("Location: $url"); exit; }

function flash($key, $msg = null) {
    if ($msg === null) {
        $m = $_SESSION['flash'][$key] ?? null;
        unset($_SESSION['flash'][$key]);
        return $m;
    }
    $_SESSION['flash'][$key] = $msg;
}

// Upload multiple images to a subfolder; returns array of relative paths
function upload_images($files, $subfolder) {
    $saved = [];
    if (empty($files['name'][0])) return $saved;

    $dir = UPLOAD_DIR . '/' . $subfolder;
    if (!is_dir($dir)) mkdir($dir, 0755, true);

    $allowed = ['jpg','jpeg','png','gif','webp'];
    $count = count($files['name']);
    for ($i = 0; $i < $count; $i++) {
        if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;
        $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) continue;
        $name = uniqid('img_', true) . '.' . $ext;
        $target = $dir . '/' . $name;
        if (move_uploaded_file($files['tmp_name'][$i], $target)) {
            $saved[] = $subfolder . '/' . $name;
        }
    }
    return $saved;
}

function delete_image_file($relativePath) {
    $full = UPLOAD_DIR . '/' . $relativePath;
    if (is_file($full)) @unlink($full);
}
