<?php
namespace App\models\Logistic\Api\Custom\Client;
use App\models\Logistic\Api\Custom\AbstractClient;
use App\models\Logistic\Api\Custom\ClientConfig;
use Pheanstalk\Exception;

class Ftp extends AbstractClient{
    protected $xml;
    protected $client;
    protected $clientConfig;
    protected $filePath;
    public function __construct(ClientConfig $config){
        $this->clientConfig=$config;
    }
    public function get(){

    }
    public function send()
    {
        $client = $this->getClient();
        $fileHander = fopen($this->filePath,'r');
        $result = \ftp_fput($client,basename($this->filePath),$fileHander,FTP_ASCII);
        return $result;
    }
    protected function getClient(){
        if(empty($this->client)){
            $configInfo = $this->clientConfig->getConfig();
            $ftp = \ftp_connect($configInfo['host'],$configInfo['port'],90);
            if(!$ftp){
                throw new Exception('ftp connect error');
            }
            \ftp_login($ftp,$configInfo['username'],$configInfo['password']);
            \ftp_pasv($ftp,false);
            if($configInfo['path']){
               \ftp_chdir($ftp,$configInfo['path']);
            }
            $this->client=$ftp;
            //var_dump($this->client);
        }
        return $this->client;
    }
    public function setSendInf(...$sendInf)
    {
        $filePath = $sendInf[0];
        $this->xml = $filePath;
        $this->filePath = $sendInf[0];
        return $this;
    }
    public function __destruct()
    {
        if($this->client) {
            \ftp_close($this->client);
        }
    }
}
