<?php
/**
 * File Editor API — Read file content (admin only)
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
header('Content-Type: application/json');

$user = auth_user();
if (($user['role'] ?? '') !== 'admin') {
    http_response_code(403); echo json_encode(['ok'=>false,'error'=>'Admin only']); exit;
}

$ROOT = realpath(__DIR__ . '/../../');
$rel  = trim($_GET['path'] ?? '', '/\\');
if (!$rel) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'No path']); exit; }

$abs = realpath($ROOT . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $rel));

// Security: must be inside project root
if (!$abs || strpos($abs, $ROOT) !== 0) {
    http_response_code(403); echo json_encode(['ok'=>false,'error'=>'Access denied']); exit;
}

// Whitelist extensions
$ext = strtolower(pathinfo($abs, PATHINFO_EXTENSION));
$allowed = ['php','css','js','html','json','txt','sql','md','htaccess','yml','yaml','xml'];
if (!in_array($ext, $allowed, true) && basename($abs) !== '.htaccess') {
    http_response_code(400); echo json_encode(['ok'=>false,'error'=>'File type not editable']); exit;
}

if (!is_file($abs)) {
    http_response_code(404); echo json_encode(['ok'=>false,'error'=>'File not found']); exit;
}

$content = file_get_contents($abs);
echo json_encode([
    'ok'      => true,
    'content' => $content,
    'size'    => filesize($abs),
    'mtime'   => date('d/m/Y H:i:s', filemtime($abs)),
    'ext'     => $ext,
]);
