<?php
declare(strict_types=1);
session_start();

define('APP_ROOT', dirname(__DIR__));
define('DATA_DIR', APP_ROOT . '/data');
define('FRAME_DIR', APP_ROOT . '/frames');

function config_path(): string {
    return DATA_DIR . '/config.json';
}

function load_config(): array {
    $path = config_path();
    if (!file_exists($path)) {
        return [
            'siteTitle' => 'City Boy Movement Photo Frame',
            'footerText' => 'Powered by City Media Pro | Contact: +234 809 945 2398',
            'adminPassword' => 'cityboyadmin',
            'frames' => []
        ];
    }
    $json = file_get_contents($path);
    $data = json_decode($json ?: '{}', true);
    return is_array($data) ? $data : [];
}

function save_config(array $config): bool {
    return file_put_contents(config_path(), json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) !== false;
}

function json_response(array $data, int $status = 200): void {
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

function require_post(): void {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
        json_response(['ok' => false, 'message' => 'POST required.'], 405);
    }
}

function is_admin(): bool {
    return !empty($_SESSION['is_admin']);
}

function require_admin_api(): void {
    if (!is_admin()) {
        json_response(['ok' => false, 'message' => 'Unauthorized.'], 401);
    }
}

function e(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
