<?php 

namespace App\Bundle\Infoclinica;

class Rest
{
    private $client;

    public function __construct()
    {
        $this->client = Client::init();
    }

    public function getRecords()
    {
        $path = '/records/list?';
        $path .= 'st=19900101';
        $path .= '&en=21000101';
        $path .= '&draw=1';
        $path .= '&columns[0][data]=0';
        $path .= '&columns[0][name]=';
        $path .= '&columns[0][searchable]=true';
        $path .= '&columns[0][orderable]=false';
        $path .= '&columns[0][search][value]=';
        $path .= '&columns[0][search][regex]=false';
        $path .= '&columns[1][data]=1';
        $path .= '&columns[1][name]=';
        $path .= '&columns[1][searchable]=true';
        $path .= '&columns[1][orderable]=false';
        $path .= '&columns[1][search][value]=';
        $path .= '&columns[1][search][regex]=false';
        $path .= '&columns[2][data]=filialName';
        $path .= '&columns[2][name]=';
        $path .= '&columns[2][searchable]=true';
        $path .= '&columns[2][orderable]=false';
        $path .= '&columns[2][search][value]=';
        $path .= '&columns[2][search][regex]=false';
        $path .= '&columns[3][data]=checkData';
        $path .= '&columns[3][name]=';
        $path .= '&columns[3][searchable]=true';
        $path .= '&columns[3][orderable]=false';
        $path .= '&columns[3][search][value]=';
        $path .= '&columns[3][search][regex]=false';
        $path .= '&columns[4][data]=payment';
        $path .= '&columns[4][name]=';
        $path .= '&columns[4][searchable]=true';
        $path .= '&columns[4][orderable]=false';
        $path .= '&columns[4][search][value]=';
        $path .= '&columns[4][search][regex]=false';
        $path .= '&columns[5][data]=';
        $path .= '&columns[5][name]=';
        $path .= '&columns[5][searchable]=true';
        $path .= '&columns[5][orderable]=false';
        $path .= '&columns[5][search][value]=';
        $path .= '&columns[5][search][regex]=false';
        $path .= '&start=0';
        $path .= '&length=20';
        $path .= '&search[value]=';
        $path .= '&search[regex]=false';
        
        $data = $this->client
            ->clearParams()
            ->setPath($path)
            ->exec()->dataResponse;
        
        if (! empty($data['response']['data'])) {
            foreach ($data['response']['data'] as $key => $dataItem) {
                $data['response']['data'][$key]['workDate'] = date('d-m-Y', strtotime($dataItem['workDate']));
            }
        }

        return $data;
    }

    public function deleteRecord($id, $fid)
    {
        $path = '/api/reservation/reserve?';
        $path .= 'reserveId='. $id;
        $path .= '&filialId=' . $fid;

        $this->client
            ->clearParams()
            ->setMethod('DELETE')
            ->setPath($path)
            ->exec()->dataResponse;
    }

    public function anonymousReserve($data = [])
    {
        $data = $this->client->setParams($data)
            ->setPath('/api/reservation/anonymous-reserve')
            ->exec()
            ->dataResponse;

        return $data;       
    }

    public function getProfile($fio, $password)
    {
        $path = '/profile';
        
        $data = $this->client->setFormParams([
            'fio' => $fio,
            'password.password' => $password,
            'password.confirm' => $password
        ])->setPath('/profile')->exec()->dataResponse;

        return $data; 
    }

    
    public function getPayments()
    {
        $path = '/payments/list';

        $data = $this->client
            ->clearParams()
            ->setPath($path)
            ->exec()->dataResponse;
        
        if (! empty($data['response']['data'])) {
            foreach ($data['response']['data'] as $key => $dataItem) {
                $data['response']['data'][$key]['date'] = date('d-m-Y', strtotime($dataItem['date']));
            }
        }

        return $data;
    }

    public function getBonus()
    {
        $path = '/bonus';
        
        return $this->client
            ->clearParams()
            ->setPath($path)
            ->exec()->dataResponse;
    }

    public function getReferrals()
    {
        $path = '/referrals/list';
        
        return $this->client
            ->clearParams()
            ->setPath($path)
            ->exec()->dataResponse;
    }

    public function getCaseHistory()
    {
        $path = '/case-history/filter?st=19900101&en=' . date('Ymd');
        $data = $this->client
            ->clearParams()
            ->setPath($path)
            ->exec()->dataResponse;

        if (! empty($data['response']['data'])) {
            foreach ($data['response']['data'] as $key => $dataItem) {
                $data['response']['data'][$key]['date'] = date('d-m-Y', strtotime($dataItem['date']));
            }
        }

        return $data;
    }

    public function reserve($data = [])
    {
        $data = $this->client->setBodyParams($data)
            ->setPath('/api/reservation/reserve')
            ->exec()
            ->dataResponse;

        return $data;
    }

    public function login($email, $password)
    {
        try {
            $data = $this->client->setBodyParams([
                'formKey' => 'pcode',
                'password' => $password,
                'username' => $email
            ])->setPath('/login')->exec()->dataResponse;

            if ($data['response']['success'] == true) {
                setcookie('WR_SESSION', $data['cookies']['WR_SESSION'], []);
                setcookie('WR_DETAIL', $data['cookies']['WR_DETAIL'], []);
                setcookie('PLAY_SESSION', $data['cookies']['PLAY_SESSION'], []);
            }

            return $data;
        } catch (Exception $e) {
            $data['response']['success'] = false;
            $data['error']['message'] = $e->getMessage(); 
            
            return $data;  
        }
    }

    public function loginEsia()
    {
        $params = [
            "authType" => 'esia',
            "esiaSdk" => '1',
            "newWindow" => 'true',
            "redirectUrl" => "http://cabinet.sovamed.ru/"
        ];

        $data = $this->client
            ->setPath('/esia/esia-login-sdk')
            ->raw($params);

        return $data;
    }

    public function getUser()
    {
        return $this->client
            ->setPath('/logged-in')
            ->clearParams()
            ->exec()
            ->dataResponse;
    }

    public function logout()
    {
        return $this->client
            ->setPath('/logout')
            ->clearParams()
            ->exec()
            ->dataResponse;
    }

    public function getFilials()
    {
        return $this->client
            ->clearParams()
            ->setPath('/filials/list')
            ->exec()->dataResponse;
    }

    public function getDepartments()
    {
        return $this->client
            ->clearParams()
            ->setPath('/specialists/departments')
            ->exec()->dataResponse;
    }

    public function getSpecialists($departments, $onlineMode = 0)
    {   
        $path = '/specialists/doctors?departments=' . $departments;
        $path .= '&onlineMode='. $onlineMode;
        
        return $this->client
            ->clearParams()
            ->setPath($path)
            ->exec()->dataResponse;
    }

    public function getInterval($sid, $did, $date, $fid = NULL, $onlineMode = 1)
    {
        if (is_array($date)) {
            $st = strtotime($date['startInterval']);
            $en = strtotime($date['endInterval']);
        } else {
            $st = strtotime('first day of this month', strtotime($date));
            $en = strtotime('last day of this month', strtotime($date));
        }

        $path = '/api/reservation/intervals?dcode='. $sid;
        $path .= '&spec='. $did;
        $path .= '&st='. date("Ymd", $st);
        $path .= '&en='. date("Ymd", $en);
        $path .= '&onlineMode=' . ($onlineMode ? 1 : 0);
        
        if (! empty($fid)) {
            $path .= '&filialId='. $fid;
            $path .= '&inFilials='. $fid;
        }

        $intervals = $this->client
            ->clearParams()
            ->setPath($path)
            ->exec()->dataResponse;

        $dataResponse = [];
        if (isset($intervals['response']['data'])) {
            foreach ($intervals['response']['data'] as $data) {
                if (isset($data['workdates'])) {
                    foreach ($data['workdates'] as $key => $workdates) {
                        foreach ($workdates as $workdate => $item) {
                            $workDate = \DateTime::createFromFormat(
                                'Ymd', 
                                $workdate
                            );

                            $intervalKey = 0;

                            for ($i=0; $i < count($item); $i++) { 
                                foreach ($item[$i]['intervals'] as $intervaldata) {
                                    $dataResponse[$workdate][$intervalKey]['workDate'] = $workDate;
                                    $dataResponse[$workdate][$intervalKey]['schedident'] = $item[$i]['schedident'];
                                    $dataResponse[$workdate][$intervalKey]['time'] = $intervaldata['time'];
                                    $dataResponse[$workdate][$intervalKey]['isFree'] = $intervaldata['isFree'];
                                    $dataResponse[$workdate][$intervalKey]['rNum'] = $item[$i]['rnum'];
                                    $intervalKey++;
                                }
                            }
                        }
                    }
                }
            }
        }
        
        return $dataResponse;
    }

    public function getSchedule($sid, $did, $date, $fid = NULL, $onlineMode = 1)
    {
        if (is_array($date)) {
            $st = strtotime($date['startInterval']);
            $en = strtotime($date['endInterval']);
        } else {
            $st = strtotime('first day of this month', strtotime($date));
            $en = strtotime('last day of this month', strtotime($date));
        }

        $path = '/api/reservation/schedule?doctor='. $sid;
        $path .= '&speclist='. $did;
        $path .= '&onlineMode=' . ($onlineMode ? 1 : 0);
        $path .= '&st='. date("Ymd", $st);
        $path .= '&en='. date("Ymd", $en);

        if (! empty($fid)) {
            $path .= '&filialId='. $fid;
        }

        return $this->client
            ->clearParams()
            ->setPath($path)
            ->exec()->dataResponse;
    }

    public function forgot($email)
    {
        return $this->client
            ->clearParams()
            ->setPath('/forgot-password?username=' . $email)
            ->exec()->dataResponse;
    }

    public function changePassword($pwdToken, $smsCode, $password)
    {
        return $this->client->setFormParams([
            'pwdToken' => $pwdToken,
            'code' => $smsCode,
            'password.password' => $password,
            'password.confirm' => $password
        ])->setPath('/change-password-web')->exec()->dataResponse;
    }

    public function register($data = [])
    {
        try {
            $birthDate = $data['registration_form']['birthDate']['day'];
            $birthDate .= '.';
            $birthDate .= $data['registration_form']['birthDate']['month'];
            $birthDate .= '.';
            $birthDate .= $data['registration_form']['birthDate']['year'];

            $data = $this->client->setFormParams([
                'birthDate' => $birthDate,
                'accept' => 'true',
                'refuseCall' => 'true',
                'refuseSms' => 'true',
                'confirmed' => '',
                'checkData' => '',
                'firstName' => $data['registration_form']['firstName'],
                'lastName' => $data['registration_form']['lastName'],
                'middleName' => $data['registration_form']['middleName'],
                'email' => $data['registration_form']['email'],
                'phone' => $data['registration_form']['phone'],
                'gender' => $data['registration_form']['gender'],
                'captcha' => $data['g-recaptcha-response'],
                'viewtype' => 1
            ])->setPath('/registration')->exec()->dataResponse;

            if ($data['response']['success'] == true) {
                setcookie('PLAY_SESSION', $data['cookies']['PLAY_SESSION'], []);
            }

            return $data;
        } catch (\Exception $e) {
            $data['response']['success'] = false;
            $data['error']['message'] = $e->getMessage(); 
            
            return $data;
        }
    }

    public function confirm($rToken, $smsCode, $password)
    {
        $data = $this->client->setFormParams([
            'smsCode' => $smsCode,
            'password.password' => $password,
            'password.confirm' => $password
        ])->setPath('/registration/confirm?rToken='. $rToken)->exec()->dataResponse;

        return $data;
    }

    public function payment()
    {
        $params = [
            'id' => 43229262,
            'filial' => 4,
            'amt' => '1200.00',
            'errorUrl' => "https://sova.infoclinica.ru/payments",
            'magazineId' => "5ed8acaa27734416bde98c89",
            'paymethod' => "AC",
            'status' => ['id' => 0, 'name' => "NotPaid"],
            'successurl' => "https://sova.infoclinica.ru/payments",
        ];
        // var_dump($this->getUser());
        $data = $this->client
            ->setPath('/payments/testApiV3')
            ->setBodyParams($params)
            ->exec()->dataResponse;

        return $data;
    }
}