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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); echo json_encode(['ok'=>false,'error'=>'POST only']); exit;
}

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

$body = json_decode(file_get_contents('php://input'), true);
$rel     = trim($body['path'] ?? '', '/\\');
$content = $body['content'] ?? null;
$token   = $body['csrf_token'] ?? '';

if (!csrf_verify($token)) {
    http_response_code(419); echo json_encode(['ok'=>false,'error'=>'CSRF validation failed']); exit;
}
if (!$rel || $content === null) {
    http_response_code(400); echo json_encode(['ok'=>false,'error'=>'Missing path or content']); exit;
}

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

if (!$abs || strpos($abs, $ROOT) !== 0) {
    http_response_code(403); echo json_encode(['ok'=>false,'error'=>'Access denied']); exit;
}

$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;
}

// Create backup
$backupDir = $ROOT . '/storage/editor_backups/' . date('Ymd');
if (!is_dir($backupDir)) @mkdir($backupDir, 0755, true);
$backupFile = $backupDir . '/' . basename($abs) . '.' . time() . '.bak';
@copy($abs, $backupFile);

// Write
$bytes = file_put_contents($abs, $content, LOCK_EX);
if ($bytes === false) {
    http_response_code(500); echo json_encode(['ok'=>false,'error'=>'Failed to write file — check permissions']); exit;
}

// Log
$pdo = crm_pdo();
gp_log_action($pdo, 'FILE_EDIT', 'file', 0, 'Edited: ' . $rel . ' (' . $bytes . ' bytes)');

echo json_encode([
    'ok'    => true,
    'bytes' => $bytes,
    'mtime' => date('d/m/Y H:i:s'),
]);
