<?php
require_once 'auth_check.php';
require_once 'db.php';
session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['path']) || !isset($data['content'])) {
        throw new Exception('Missing parameters');
    }

    $db = getDB1Connection();
    $query = $db->prepare("SELECT staff_directory FROM utilisateurs WHERE id = ?");
    $query->execute([$_SESSION['user_id']]);
    $result = $query->fetch(PDO::FETCH_ASSOC);
    
    if (!$result || !$result['staff_directory']) {
        throw new Exception('Staff directory not configured');
    }

    $rootPath = $result['staff_directory'];
    $filePath = $rootPath . $data['path'];

    if (!str_starts_with(realpath($filePath), realpath($rootPath))) {
        throw new Exception('Access denied');
    }

    if (!file_put_contents($filePath, $data['content'])) {
        throw new Exception('Failed to save file');
    }

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}