<?php
header('Content-Type: application/json; charset=utf-8');
ob_start();
session_start();
$response = ['success' => false, 'message' => ''];
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') throw new Exception('POST only');
if (empty($_SESSION['sftp_connected']) || empty($_SESSION['sftp_config'])) throw new Exception('Not connected');
require_once __DIR__ . '/SFTPconnector.php';
$config = $_SESSION['sftp_config'];
$input = json_decode(file_get_contents('php://input'), true);
$path = $input['path'] ?? '';
$content = $input['content'] ?? '';
if (!$path) throw new Exception('Missing file path');
$connector = extension_loaded('ssh2') ? new SFTPConnector() : new SystemSFTPConnector();
$connect = $connector->connect($config['host'], (int)$config['port'], $config['username'], $config['password']);
if ($connect !== true) throw new Exception("Connect failed: $connect");
$tmp = tempnam(sys_get_temp_dir(), 'insta_');
file_put_contents($tmp, $content);
$result = $connector->uploadFile($tmp, $path);
unlink($tmp);
if ($result === true) {
$response['success'] = true;
$response['message'] = "File '$path' created successfully.";
} else {
throw new Exception($result);
}
} catch (Throwable $e) {
$response['success'] = false;
$response['message'] = $e->getMessage();
}
if (ob_get_length()) ob_clean();
echo json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);