<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Uploadmedias Model
 *
 * @property \App\Model\Table\ClientsTable&\Cake\ORM\Association\BelongsTo $Clients
 * @property \App\Model\Table\RtgLetterImagesTable&\Cake\ORM\Association\BelongsTo $RtgLetterImages
 *
 * @method \App\Model\Entity\Uploadmedia get($primaryKey, $options = [])
 * @method \App\Model\Entity\Uploadmedia newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\Uploadmedia[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Uploadmedia|false save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Uploadmedia saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Uploadmedia patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\Uploadmedia[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\Uploadmedia findOrCreate($search, callable $callback = null, $options = [])
 */
class UploadmediasTable extends AppTable
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('uploadmedias');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Clients', [
            'foreignKey' => 'client_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('RtgLetterImages', [
            'foreignKey' => 'rtg_letter_image_id',
            'joinType' => 'INNER'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmptyString('id', null, 'create');

        $validator
            ->scalar('image_path')
            ->maxLength('image_path', 100)
            ->requirePresence('image_path', 'create')
            ->notEmptyFile('image_path');

        $validator
            ->dateTime('created_on')
            ->requirePresence('created_on', 'create')
            ->notEmptyDateTime('created_on');

        $validator
            ->dateTime('modified_on')
            ->requirePresence('modified_on', 'create')
            ->notEmptyDateTime('modified_on');

        return $validator;
    }

    public function getUploadMediaByClientId($client_id){
        $result = [];
        if($client_id > 0){
            $media = $this->find()->where(['client_id'=>$client_id])->toArray();
            
            if(!empty($media)){
                $result = $media;
            }
        }
        
        return $result;
    }


    public function uploadMedia($inputData) {
        
        if (isset($inputData['identification']) && !empty($inputData['identification']['name'])) {
            $rtg_letter_image_id = 1;
            $image_path = 'identification';
            $this->uploadClientDocs($inputData, $image_path, $rtg_letter_image_id);
        }

        if (isset($inputData['mail_doc']) && !empty($inputData['mail_doc']['name'])) {
            $rtg_letter_image_id = 2;
            $image_path = 'mail_doc';
            $this->uploadClientDocs($inputData, $image_path, $rtg_letter_image_id);
        }

        if (isset($inputData['ssn']) && !empty($inputData['ssn']['name'])) {
            $rtg_letter_image_id = 3;
            $image_path = 'ssn';
            $this->uploadClientDocs($inputData, $image_path, $rtg_letter_image_id);
        }

        if (isset($inputData['state_photo_id']) && !empty($inputData['state_photo_id']['name'])) {
            $rtg_letter_image_id = 4;
            $image_path = 'state_photo_id';
            $this->uploadClientDocs($inputData, $image_path, $rtg_letter_image_id);
        }

        if (isset($inputData['notarized_letter']) && !empty($inputData['notarized_letter']['name'])) {
            $rtg_letter_image_id = 5;
            $image_path = 'notarized_letter';
            $this->uploadClientDocs($inputData, $image_path, $rtg_letter_image_id);
        }

        if (isset($inputData['cr_report']) && !empty($inputData['cr_report']['name'])) {
            $rtg_letter_image_id = 6;
            $image_path = 'cr_report';
            $this->uploadClientDocs($inputData, $image_path, $rtg_letter_image_id);
        }

        if (isset($inputData['trouble_mark_file']) && !empty($inputData['trouble_mark_file']['name'])) {
            $rtg_letter_image_id = 7;
            $image_path = 'trouble_mark_file';
            $this->uploadClientDocs($inputData, $image_path, $rtg_letter_image_id);
        }

        if (isset($inputData['item_challenge_file']) && !empty($inputData['item_challenge_file']['name'])) {
            $rtg_letter_image_id = 8;
            $image_path = 'item_challenge_file';
            $this->uploadClientDocs($inputData, $image_path, $rtg_letter_image_id);
        }
    }

    private function uploadClientDocs($inputData, $image_path, $rtg_letter_image_id) {
        $resutlt = false;
        
        $client_id = $inputData['client_id'];
        if (!empty($inputData[$image_path])) {
            $unique_name = uniqid().time() . $client_id.".jpg";
            
            //$uploadmediaTable = TableRegistry::get('uploadmedias');
            $uploadmedia = $this->newEntity();
            $uploadmedia->client_id = $client_id;
            $uploadmedia->rtg_letter_image_id = $rtg_letter_image_id;
            $image = $inputData[$image_path]['name'];
            $uploadmedia->image_path = $client_id . '/' . $unique_name;
            $uploadmedia->created_on = date("Y-m-d h:i:s");
            $uploadmedia->modified_on = date("Y-m-d h:i:s");

            if ($saved = $this->save($uploadmedia)) {
                $inserted_id = $saved->id;
                $this->uploadFile($image, $unique_name, $client_id);
                $resutlt = true;
            }
        }

        return $resutlt;
    }
    
    
    private function uploadDocsFromClient($inputData, $image_path, $rtg_letter_image_id) {
        $resutlt = false;
        
        $client_id = $inputData['client_id'];
        if (!empty($inputData[$image_path])) {
            $current_date_time = $this->getSystemCurrentTimeStamp('Y-m-d h:i:s');
            
            
            $uploadMedia = $this->find()->where(['client_id','rtg_letter_image_id'=>$rtg_letter_image_id])->first();
            
            if(!empty($uploadMedia)){
                $uploadmedia = $uploadMedia;
                $uploadmedia->modified_on = $current_date_time;
            }else{
                $uploadmedia = $this->newEntity();
                $uploadmedia->created_on = $current_date_time;
                
            }
            //$uploadmediaTable = TableRegistry::get('uploadmedias');
            
            $uploadmedia->client_id = $client_id;
            $uploadmedia->rtg_letter_image_id = $rtg_letter_image_id;
            $image = $inputData[$image_path]['name'];
            //$uploadmedia->image_path = $client_id . '/' . $unique_name;

            if ($saved = $this->save($uploadmedia)) {
                $inserted_id = $saved->id;
                $unique_name = $inserted_id."_".$client_id.$inputData[$image_path]['name'];
                if(!empty($uploadMedia)){
                    @unlink(WWW_ROOT."contact_photo/".$uploadmedia->image_path);
                }
                
                $this->photoupload($inputData[$image_path], $unique_name, $client_id);
                $this->updateAll(['image_path'=>$client_id . '/'.$unique_name],['id'=>$inserted_id]);
                $resutlt = true;
            }
        }

        return $resutlt;
    }

    public function uploadFromClientPanelPopup($inputData) {
        $result = false;
        if (isset($inputData['mail_doc']) && !empty($inputData['mail_doc']['name'])) {
            $rtg_letter_image_id = 2;
            $image_path = 'mail_doc';
            $result = $this->uploadDocsFromClient($inputData, $image_path, $rtg_letter_image_id);
        }else if (isset($inputData['state_photo_id']) && !empty($inputData['state_photo_id']['name'])) {
            $rtg_letter_image_id = 4;
            $image_path = 'state_photo_id';
            $result = $this->uploadDocsFromClient($inputData, $image_path, $rtg_letter_image_id);
        }else if(isset($inputData['ssn']) && !empty($inputData['ssn']['name'])){
            $rtg_letter_image_id = 3;
            $image_path = 'ssn';
            $result = $this->uploadDocsFromClient($inputData, $image_path, $rtg_letter_image_id);
        }

        
        return $result;
    }

    private function photoupload($image, $unique_name, $client_id) {
        if (!is_dir('contact_photo/' . $client_id)) {
            mkdir('contact_photo/' . $client_id, 0777, true);
        }

        $target_dir = 'contact_photo/' . $client_id . '/';
        $target_file = $target_dir . $unique_name;

        if (isset($image["tmp_name"]) && !empty($image["tmp_name"])) {
            move_uploaded_file($image["tmp_name"], $target_file);
            $image_size = $image["size"];
        }
    }

    private function uploadFile($image, $unique_name, $client_id) {
        
        $pos  = strpos($image, ';');
        $extension = end(explode("/",explode(':', substr($image, 0, $pos))[1]));
        
        if (!is_dir('contact_photo/' . $client_id)) {
            mkdir('contact_photo/' . $client_id, 0777, true);
        }

        $target_dir = 'contact_photo/' . $client_id . '/';
        $target_file = $target_dir . $unique_name;

        if (isset($image["tmp_name"]) && !empty($image["tmp_name"])) {
            move_uploaded_file($image["tmp_name"], $target_file);
            $image_size = $image["size"];
        }else{

            $default_base_64_string = 'data:image/jpeg;base64,';
            $extension = strtolower($extension);
            if($extension == "png"){
                $default_base_64_string = 'data:image/png;base64,';
            }else if($extension == "jpg" || $extension == "jpeg"){
                $default_base_64_string = 'data:image/jpeg;base64,';
            }else if($extension == "bmp"){
                $default_base_64_string = 'data:image/bmp;base64,';
            }
            
            $data = str_replace($default_base_64_string, '', $image);
            $data = base64_decode($data);
            //$data = str_replace('data:image/jpeg;base64,', '', $image);
            //$data = base64_decode($data);

            file_put_contents($target_file, $data);
            $image_size = filesize($target_file);
        }


        if ($image_size > UPLOAD_MEDIA_SIZE) {
            unlink($target_file);
        } 
    }
    
    
    public function getClientDocsImagesByClientId($client_id){
        
        $result = [];
        if($client_id > 0){
            
            $images = $this->find()->where(['client_id'=>$client_id])->toArray();
            if(!empty($images)){
                foreach ($images as $image){
                    $result[$image->rtg_letter_image_id] = $image->image_path;
                }
            }
        }
        return $result;
    }
    
    
    
    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
//    public function buildRules(RulesChecker $rules)
//    {
//        $rules->add($rules->existsIn(['client_id'], 'Clients'));
//        $rules->add($rules->existsIn(['rtg_letter_image_id'], 'RtgLetterImages'));
//
//        return $rules;
//    }
}
