<?php
// api/fonts.php  —  Font library management API
require_once __DIR__ . '/../config.php';
startSecureSession();
if (empty($_SESSION['admin_id'])) { jsonOut(['error' => 'Unauthorized'], 401); }

$fontsDir = BASE_PATH . '/lib/fonts';
if (!is_dir($fontsDir)) mkdir($fontsDir, 0755, true);

$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

// ── List installed fonts ──────────────────────────────────────
if ($action === 'list') {
    $fonts = [];
    foreach (glob($fontsDir . '/*.{ttf,otf,TTF,OTF}', GLOB_BRACE) as $path) {
        $name = pathinfo($path, PATHINFO_FILENAME);
        $ext  = strtolower(pathinfo($path, PATHINFO_EXTENSION));
        $file = basename($path);
        $fonts[] = [
            'file'    => $file,
            'name'    => $name,
            'ext'     => $ext,
            'size'    => filesize($path),
            'url'     => BASE_URL . '/api/fonts.php?action=serve&file=' . urlencode($file),
        ];
    }
    // Sort: bold variants after regular for display
    usort($fonts, fn($a,$b) => strcmp($a['name'], $b['name']));
    jsonOut(['fonts' => $fonts]);
}

// ── Serve a font file for browser @font-face preview ─────────
if ($action === 'serve') {
    $file = basename($_GET['file'] ?? '');
    $path = $fontsDir . '/' . $file;
    if (!$file || !file_exists($path) || !preg_match('/\.(ttf|otf)$/i', $file)) {
        http_response_code(404); exit('Not found');
    }
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    header('Content-Type: font/' . ($ext === 'otf' ? 'otf' : 'ttf'));
    header('Cache-Control: public, max-age=86400');
    readfile($path);
    exit;
}

// ── Upload font(s) ────────────────────────────────────────────
if ($action === 'upload' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $files   = $_FILES['fonts'] ?? null;
    $results = [];

    if (!$files) { jsonOut(['error' => 'No files uploaded.'], 400); }

    // Normalise single/multiple file arrays
    $fileList = [];
    if (is_array($files['name'])) {
        for ($i = 0; $i < count($files['name']); $i++) {
            $fileList[] = [
                'name'     => $files['name'][$i],
                'tmp_name' => $files['tmp_name'][$i],
                'size'     => $files['size'][$i],
                'error'    => $files['error'][$i],
            ];
        }
    } else {
        $fileList[] = $files;
    }

    foreach ($fileList as $f) {
        if ($f['error'] !== UPLOAD_ERR_OK) {
            $results[] = ['file' => $f['name'], 'ok' => false, 'msg' => 'Upload error'];
            continue;
        }
        $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['ttf', 'otf'])) {
            $results[] = ['file' => $f['name'], 'ok' => false, 'msg' => 'Only .ttf or .otf accepted'];
            continue;
        }
        if ($f['size'] > 20 * 1024 * 1024) {
            $results[] = ['file' => $f['name'], 'ok' => false, 'msg' => 'File too large (max 20 MB)'];
            continue;
        }
        // Sanitise filename: keep alphanumeric, spaces→underscore, hyphens
        $safeName = preg_replace('/[^a-zA-Z0-9\-_. ]/', '', pathinfo($f['name'], PATHINFO_FILENAME));
        $safeName = trim(preg_replace('/\s+/', '_', $safeName));
        if (!$safeName) $safeName = 'font_' . time();
        $dest = $fontsDir . '/' . $safeName . '.' . $ext;
        if (move_uploaded_file($f['tmp_name'], $dest)) {
            $results[] = [
                'file' => $safeName . '.' . $ext,
                'ok'   => true,
                'url'  => BASE_URL . '/api/fonts.php?action=serve&file=' . urlencode($safeName . '.' . $ext),
            ];
        } else {
            $results[] = ['file' => $f['name'], 'ok' => false, 'msg' => 'Could not save file'];
        }
    }
    jsonOut(['results' => $results]);
}

// ── Delete font ───────────────────────────────────────────────
if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true) ?? [];
    $file = basename($body['file'] ?? '');
    if (!$file || !preg_match('/\.(ttf|otf)$/i', $file)) {
        jsonOut(['error' => 'Invalid file.'], 400);
    }
    $path = $fontsDir . '/' . $file;
    // Protect the bundled defaults
    if (in_array($file, ['font.ttf', 'font-bold.ttf'])) {
        jsonOut(['error' => 'Cannot delete default fonts.'], 403);
    }
    if (file_exists($path)) {
        unlink($path);
        jsonOut(['ok' => true]);
    }
    jsonOut(['error' => 'File not found.'], 404);
}

jsonOut(['error' => 'Unknown action'], 400);
