<?php

namespace App\Services;

use Exception;

class FTPException extends Exception {}

class FTPManager {

    private $conn_id;
    private $mode = FTP_BINARY;

    public function getConnectionId() {
        return $this->conn_id;
    }

    public function __construct($config) {
        $this->conn_id = ftp_connect($config['host']);
        if (!$this->conn_id) {
            throw new FTPException("Unable to connect to FTP server.");
        }
        $login = ftp_login($this->conn_id, $config['username'], $config['password']);
        if (!$login) {
            throw new FTPException("Unable to login to FTP server.");
        }
        ftp_pasv($this->conn_id, true); // Pasif moda geçiş
    }

    public function setDirectory($directory) {
        if (!ftp_chdir($this->conn_id, $directory)) {
            throw new FTPException("Unable to change directory.");
        }
    }

    public function getDirectory($directory = '.') {
        $files = ftp_nlist($this->conn_id, $directory);
        return $files;
    }

    public function rename($oldName, $newName) {
        if (!ftp_rename($this->conn_id, $oldName, $newName)) {
            throw new FTPException("Unable to rename file.");
        }
        return true;
    }

    public function delete($file) {
        if (!ftp_delete($this->conn_id, $file)) {
            throw new FTPException("Unable to delete file.");
        }
        return true;
    }

    public function makeDir($dirName) {
        $result = ftp_mkdir($this->conn_id, $dirName);
        if (!$result) {
            throw new FTPException("Unable to create directory.");
        }
        return $result;
    }

    public function removeDir($dirName) {
        if (!ftp_rmdir($this->conn_id, $dirName)) {
            throw new FTPException("Unable to remove directory.");
        }
        return true;
    }

    public function upload($local, $remote) {
        if (!ftp_put($this->conn_id, $remote, $local, $this->mode)) {
            throw new FTPException("Unable to upload file.");
        }
        return true;
    }

    public function download($remote, $local = null) {
        if (is_null($local)) {
            $local = tempnam(sys_get_temp_dir(), 'FTP');
        }
        if (!ftp_get($this->conn_id, $local, $remote, $this->mode)) {
            throw new FTPException("Unable to download file.");
        }
        return $local;
    }

    public function read($remote) {
        ob_start();
        $result = ftp_get($this->conn_id, 'php://output', $remote, $this->mode);
        $output = ob_get_clean();
        if (!$result) {
            throw new FTPException("Unable to read file.");
        }
        return $output;
    }

    private function error() {
        $error = error_get_last();
        return $error['message'];
    }
}
?>
