<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require APPPATH . '/libraries/CreatorJwt.php';

class files extends CI_Controller{
    
    public function __construct(){
        parent::__construct();
        $this->objOfJwt = new CreatorJwt();
        header('Content-Type: application/json');
    }
    
    public function authBoxApi(){

        $json               = file_get_contents('752545291_rkngfmfu_config.json');
        $config             = json_decode($json);
        $private_key        = $config->boxAppSettings->appAuth->privateKey;
        $passphrase         = $config->boxAppSettings->appAuth->passphrase;
        $key                = openssl_pkey_get_private($private_key, $passphrase);
        $authenticationUrl  = 'https://api.box.com/oauth2/token';
        $claims = [
            'iss' => $config->boxAppSettings->clientID,
            'sub' => $config->enterpriseID,
            'box_sub_type' => 'enterprise',
            'aud' => $authenticationUrl,
            'jti' => base64_encode(str_shuffle('abcdefBurhan5vvjhh1237856123mnhigabcdefBurhan5vvjhh1237856123')),
            'exp' => time() + 45,
            'kid' => $config->boxAppSettings->appAuth->publicKeyID
        ];
        
        $tokenData = array( $claims, $key, 'RS512' );
        $jwtToken = $this->objOfJwt->GenerateToken($tokenData);
        $params = [
            'grant_type'    => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion'     => $jwtToken,
            'client_id'     => $config->boxAppSettings->clientID,
            'client_secret' => $config->boxAppSettings->clientSecret
        ];
        
        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_URL, "$authenticationUrl");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        
        $response       = curl_exec($ch);
        $response       = json_decode($response);
        $token          = $response->access_token;
        return $token;
    }
    
    public function upload(){
        
        $token          = $this->authBoxApi();
        
        if(!empty($token) && $token != FALSE && !empty($_FILES)){
            $customerId     = (isset($_POST['customerId'])) ? $_POST['customerId'] : getAdminId();
            $clientData     = $this->general_model->getRowById('customers', 'customerId', $customerId);
            $clientName     = $clientData->customerName;
            $folder_id      = $clientData->box_folder_id;
            $result         = (object)array();
            $shared_link    = '';
            $thumbnailUrl   = '';
            if( empty($folder_id) || $folder_id == 0 ){
                $folder_id = newBoxFolder($token, $customerId, $clientName);
                $editClient = $this->general_model->updateRowById('customers', 'customerId', $customerId, array("box_folder_id" => $folder_id));
            }else{
                $folder_id = $folder_id;
            }
            if(!empty($folder_id) && $folder_id > 0){
                $parentId       = $folder_id;
                $filePath       = $_FILES['file']['tmp_name'];
                $fileName       = $_FILES['file']['name'];
                $upload_file    = uploadBoxFile($token, $filePath, $fileName, $parentId);
                if(!empty($upload_file) && $upload_file > 0){
                    $updateFile = updateFileShared($token, $file_id = $upload_file);
                    if(!empty($updateFile)){
                        $file_data = array(
                            'customerId'    => $customerId,
                            'file_name'     => $fileName,
                            'box_id'        => $upload_file,
                            'type'          => 1,
                            'file_for'      => (isset($_POST['file_for'])) ? $_POST['file_for'] : '',
                            'order_id'      => (isset($_POST['order_id'])) ? $_POST['order_id'] : '',
                            'dateCreation'  => date('Y-m-d H:i:s')
                        );
                        $addFiles = $this->general_model->InsertRow('customers_files', $file_data);
                        
                        $getLink        = getSharedLink($token, $file_id = $upload_file);
                        $fileData       = json_decode($getLink);
                        $shared_link    = $fileData->shared_link->url;
                        $thumbnailUrl   = $fileData->shared_link->download_url;
                        $add_link       = $this->general_model->updateRowById('customers_files', 'file_id', $addFiles, array("shared_link" => $shared_link));
                        $result->status       = true;
                        $result->folder_id    = $folder_id;
                        $result->file_id      = $upload_file;
                        $result->shared_link  = $shared_link;
                    }
                }
            }
            
            $files = array(
                    'name'          => $fileName,
                    'size'          => $_FILES['file']['size'],
                    'url'           => $shared_link,
                    'thumbnailUrl'  => $thumbnailUrl,
                    'deleteUrl'     => '#',
                    'deleteType'    => null
                );
            
            $filejson = new stdClass();
            $filejson->files[] = $files;
            echo json_encode($filejson);
        }else{
            echo json_encode(array("result" => false ));
        }
    }
    
    public function download($file_id){
        
        if(isset($file_id) && !empty($file_id)){
            $file           = $this->general_model->getRowById('customers_files', 'box_id', $file_id);
            if(!empty($file)){
                header("Content-Type: image/jpeg");
                $token = $this->authBoxApi();
                if(!empty($token) && $token != FALSE){
                    $download = downloadFile($token, $file_id);
                    echo $download;
                }else{
                    echo json_encode(array("result" => false ));
                }
            }else{
                echo json_encode(array("result" => false ));
            }
        }else{
            echo json_encode(array("result" => false ));
        }
    }

}





