<?php
// ── CY Admin Panel — Config ──
ob_start(); // Buffer output to prevent "headers already sent" errors
if (session_status() === PHP_SESSION_NONE) session_start();


// Database credentials
define('DB_HOST', 'localhost');
define('DB_USER', 'rojbpgfm_cy_consultancy');
define('DB_PASS', 'kKJGWrpD])WB');
define('DB_NAME', 'rojbpgfm_cy_consultancy');

// ── URL & Path Resolution (Windows + Linux safe) ──
$protocol    = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host        = $_SERVER['HTTP_HOST'];

// Normalize all slashes to forward slash (Windows safe)
$adminRootFs = str_replace('\\', '/', dirname(__DIR__));  // .../cy-php/admin
$siteRootFs  = str_replace('\\', '/', dirname($adminRootFs)); // .../cy-php
$docRoot     = rtrim(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), '/');

// Get URL path portion by stripping document root
$adminUrlPath = str_replace($docRoot, '', $adminRootFs);
$siteUrlPath  = str_replace($docRoot, '', $siteRootFs);

// Fallback: if path replacement didn't work, derive from SCRIPT_NAME
if (empty($adminUrlPath) || $adminUrlPath === $adminRootFs) {
    // Use SCRIPT_NAME approach as fallback
    $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
    // Walk up until we find 'admin' in path
    $parts = explode('/', trim($scriptDir, '/'));
    $adminIdx = array_search('admin', $parts);
    if ($adminIdx !== false) {
        $adminUrlPath = '/' . implode('/', array_slice($parts, 0, $adminIdx + 1));
        $siteUrlPath  = '/' . implode('/', array_slice($parts, 0, $adminIdx));
    } else {
        $adminUrlPath = $scriptDir;
        $siteUrlPath  = dirname($scriptDir);
    }
}

define('ADMIN_URL', $protocol . '://' . $host . rtrim($adminUrlPath, '/'));
define('SITE_URL',  $protocol . '://' . $host . rtrim($siteUrlPath, '/'));
define('ADMIN_ROOT', str_replace('\\', '/', dirname(__DIR__)));
define('SITE_ROOT',  str_replace('\\', '/', dirname(dirname(__DIR__))));
define('UPLOAD_DIR', SITE_ROOT . '/assets/uploads/');
define('UPLOAD_URL', SITE_URL . '/assets/uploads/');

// ── Database ──
function db(): mysqli {
    static $conn = null;
    if ($conn === null) {
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($conn->connect_error) {
            die('<div style="font-family:sans-serif;padding:40px;background:#fee2e2;color:#991b1b;border-radius:12px;margin:20px;border:1px solid #fca5a5">
                <h2 style="margin-bottom:10px">⚠ Database Connection Failed</h2>
                <p>' . htmlspecialchars($conn->connect_error) . '</p>
                <p style="margin-top:10px;font-size:14px">Edit <code>admin/includes/config.php</code> and set correct DB credentials, then run <code>admin/setup.sql</code> in phpMyAdmin.</p>
            </div>');
        }
        $conn->set_charset('utf8mb4');
    }
    return $conn;
}

// ── Auth ──
function requireLogin(): void {
    if (empty($_SESSION['cy_admin_id'])) {
        header('Location: ' . ADMIN_URL . '/login.php');
        exit;
    }
}
function isLoggedIn(): bool { return !empty($_SESSION['cy_admin_id']); }
function currentAdmin(): array {
    if (empty($_SESSION['cy_admin_id'])) return [];
    return [
        'id'        => $_SESSION['cy_admin_id'],
        'username'  => $_SESSION['cy_admin_user'] ?? '',
        'full_name' => $_SESSION['cy_admin_name'] ?? '',
        'role'      => $_SESSION['cy_admin_role'] ?? 'editor',
    ];
}

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

function slug(string $text): string {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9\s-]/', '', $text);
    $text = preg_replace('/[\s-]+/', '-', $text);
    return trim($text, '-') ?: 'page-' . time();
}

function redirect(string $url): void { header('Location: ' . $url); exit; }

function flash(string $msg, string $type = 'success'): void {
    $_SESSION['cy_flash'] = ['msg' => $msg, 'type' => $type];
}
function getFlash(): ?array {
    if (!empty($_SESSION['cy_flash'])) { $f = $_SESSION['cy_flash']; unset($_SESSION['cy_flash']); return $f; }
    return null;
}

function getSetting(string $key, string $default = ''): string {
    try {
        $st = db()->prepare("SELECT setting_value FROM site_settings WHERE setting_key=? LIMIT 1");
        $st->bind_param('s', $key); $st->execute();
        $r = $st->get_result()->fetch_assoc();
        return $r ? ($r['setting_value'] ?? $default) : $default;
    } catch(Exception $e) { return $default; }
}

function handleUpload(string $inputName, string $subfolder = 'uploads'): ?string {
    if (empty($_FILES[$inputName]['name'])) return null;
    $file = $_FILES[$inputName];
    if ($file['error'] !== UPLOAD_ERR_OK) return null;
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','gif','webp','svg','ico'])) return null;
    $dir = SITE_ROOT . '/assets/uploads/' . $subfolder . '/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $filename = 'cy_' . uniqid() . '.' . $ext;
    if (move_uploaded_file($file['tmp_name'], $dir . $filename))
        return 'assets/uploads/' . $subfolder . '/' . $filename;
    return null;
}
