<?php

if (!defined('ABSPATH'))
    die('Restricted Access');

class JSJOBSuploads {

    private $uploadfor;
    private $companyid;
    private $resumeid;

    function jsjobs_upload_dir( $dir ) {
        $form_request = JSJOBSrequest::getVar('form_request');
        if($form_request == 'jsjobs' || ($this->uploadfor == 'resumephoto' || $this->uploadfor == 'resumefiles')){ // Patch b/c of resume is ajax base
            $datadirectory = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('data_directory');
            // test code
            $file = @fopen($dir['basedir'].'/'.$datadirectory."/index.html", 'w');
            if($file){
                fclose($file);
            }
            
            $path = $datadirectory . '/data';
            // // test code
            $file = @fopen($dir['basedir'].'/'.$path."/index.html", 'w');
            if($file){
                fclose($file);
            }
            //
            $apath = $path;

            if($this->uploadfor == 'company'){
                $path = $path . '/employer/comp_'.$this->companyid.'/logo';
            }elseif($this->uploadfor == 'resumephoto'){
                $path = $path . '/jobseeker/resume_'.$this->resumeid.'/photo';
            }elseif($this->uploadfor == 'resumefiles'){
                $path = $path . '/jobseeker/resume_'.$this->resumeid.'/resume';
            }
            // // test code
            $file = @fopen($path."/index.html", 'w');
            if($file){
                fclose($file);
            }
            //

            $userpath = $path;
            $array = array(
                'path'   => $dir['basedir'] . '/' . $userpath,
                'url'    => $dir['baseurl'] . '/' . $userpath,
                'subdir' => '/'. $userpath,
            ) + $dir;
            return $array;
        }else{
            return $dir;
        }
    }

    function uploadCompanyLogo($id){
        $file_size = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('company_logofilezize');
        if (!function_exists('wp_handle_upload')) { 
            require_once( ABSPATH . 'wp-admin/includes/file.php' ); 
        }
        $this->companyid = $id;
        $this->uploadfor = 'company';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jsjobs_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        $filename = '';
        $return = 1;
        $file = array(
                'name'     => sanitize_file_name($_FILES['logo']['name']),
                'type'     => sanitize_mime_type($_FILES['logo']['type']),
                'tmp_name' => sanitize_mime_type($_FILES['logo']['tmp_name']),
                'error'    => sanitize_key($_FILES['logo']['error']),
                'size'     => sanitize_key($_FILES['logo']['size'])
                );
        $uploadfilesize = $file['size'] / 1024; //kb
        $key = JSJOBSincluder::getJSModel('company')->getMessagekey();        
        if($uploadfilesize > $file_size){
            JSJOBSMessages::setLayoutMessage(__('File size is greater then allowed file size', 'js-jobs'), 'error',$key);
            $return = 5;
        }else{
            $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['logo']['name']));
            if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
                $image_file_types = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('image_file_type');
                if(jsjobslib::jsjobs_strstr($image_file_types, $filetyperesult['ext'])){
                    $result = wp_handle_upload($file, array('test_form' => false));
                    if ( $result && ! isset( $result['error'] ) ) {
                        $filename = jsjobslib::jsjobs_basename( $result['file'] );
                        $imageresult[0] = $result['file'];
                        $imageresult[1] = $result['url'];
                    } else {
                        /**
                         * Error generated by _wp_handle_upload()
                         * @see _wp_handle_upload() in wp-admin/includes/file.php
                         */
						JSJOBSMessages::setLayoutMessage($result['error'], 'error','company');
                    }
                }else{
                    $return = 5;
                }
            }else{
                $return = 6;
            }

        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jsjobs_upload_dir'));
        if($return == 1){
            $query = "UPDATE `".jsjobs::$_db->prefix."js_job_companies` SET logofilename = '".$filename."', logoisfile = 1 WHERE id = ".$id;
            jsjobs::$_db->query($query);

            // index code
            $datadirectory = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('data_directory');
            $dir = wp_upload_dir();
            
            $file = @fopen($dir['basedir'].'/'.$datadirectory."/index.html", 'w');
            if($file){
                fclose($file);
            }
            $path = $datadirectory . '/data';
            $file = @fopen($dir['basedir'].'/'.$path."/index.html", 'w');
            if($file){
                fclose($file);
            }
            $file = @fopen($dir['basedir'].'/'.$path."/employer/index.html", 'w');
            if($file){
                fclose($file);
            }
            $file = @fopen($dir['basedir'].'/'.$path."/employer/comp_".$this->companyid."/index.html", 'w');
            if($file){
                fclose($file);
            }
            $file = @fopen($dir['basedir'].'/'.$path."/employer/comp_".$this->companyid."/logo/index.html", 'w');
            if($file){
                fclose($file);
            }
        }else{
            $query = "UPDATE `".jsjobs::$_db->prefix."js_job_companies` SET logofilename = '', logoisfile = -1 WHERE id = ".$id;
            jsjobs::$_db->query($query);
        }

/*
        // cropingg and resizzing images
        $wpdir = wp_upload_dir();
        $data_directory = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('data_directory');
        $path = $wpdir['basedir'] . '/' . $data_directory . '/data/employer/comp_' .$id.'/logo' ;
        
        if(is_array($imageresult) && !empty($imageresult)){
            $file_size = filesize($imageresult[0]);
            $temp_file_name = jsjobslib::jsjobs_basename( $imageresult[0] );
            $imageresult[1] = jsjobslib::jsjobs_str_replace($temp_file_name, '', $imageresult[1]);
           // to add sufix of image s m l ms
            $file_name = 'jsjb-logo_'.$temp_file_name;
            $this->createThumbnail($file_name,322,291,$imageresult[0],$path);
            // need to store image name in above code.
        }
  */
    

        return $return;
    }


    function uploadResumePhoto($id){
        if(!is_numeric($id)) return false;
        $this->resumeid = $id;
        $this->uploadfor = 'resumephoto';

        if (!function_exists('wp_handle_upload')) { 
            require_once( ABSPATH . 'wp-admin/includes/file.php' ); 
        }
        $this->companyid = $id;
        $this->uploadfor = 'resumephoto';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jsjobs_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        $filename = '';
        $return = true;
        $file = array(
                'name'     => sanitize_file_name($_FILES['photo']['name']),
                'type'     => sanitize_mime_type($_FILES['photo']['type']),
                'tmp_name' => sanitize_mime_type($_FILES['photo']['tmp_name']),
                'error'    => sanitize_key($_FILES['photo']['error']),
                'size'     => sanitize_key($_FILES['photo']['size'])
                );
        $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['photo']['name']));
        if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
            $image_file_types = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('image_file_type');
            if(jsjobslib::jsjobs_strstr($image_file_types, $filetyperesult['ext'])){
                $result = wp_handle_upload($file, array('test_form' => false));
                if ( $result && ! isset( $result['error'] ) ) {
                    $filename = jsjobslib::jsjobs_basename( $result['file'] );
                } else {
                    /**
                     * Error generated by _wp_handle_upload()
                     * @see _wp_handle_upload() in wp-admin/includes/file.php
                     */
					JSJOBSMessages::setLayoutMessage($result['error'], 'error','resume');
                }
            }else{
                $return = null;
            }
        }else{
            $return = 6;
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jsjobs_upload_dir'));
        if($return == true){
            $query = "UPDATE `".jsjobs::$_db->prefix."js_job_resume` SET photo = '".$filename."' WHERE id = ".$id;
            jsjobs::$_db->query($query);

             // index code
            $datadirectory = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('data_directory');
            $dir = wp_upload_dir();
            
            $file = @fopen($dir['basedir'].'/'.$datadirectory."/index.html", 'w');
            if($file){
                fclose($file);
            }
            $path = $datadirectory . '/data';
            $file = @fopen($dir['basedir'].'/'.$path."/index.html", 'w');
            if($file){
                fclose($file);
            }
            $file = @fopen($dir['basedir'].'/'.$path."/jobseeker/index.html", 'w');
            if($file){
                fclose($file);
            }
            $file = @fopen($dir['basedir'].'/'.$path."/jobseeker/resume_".$id."/index.html", 'w');
            if($file){
                fclose($file);
            }
            $file = @fopen($dir['basedir'].'/'.$path."/jobseeker/resume_".$id."/photo/index.html", 'w');
            if($file){
                fclose($file);
            }
        }
        return $return;
    }


    function uploadResumeFiles($id){
        if(!is_numeric($id)) return false;
        $return = true;
        if (!function_exists('wp_handle_upload')) { 
            require_once( ABSPATH . 'wp-admin/includes/file.php' ); 
        }
        $this->resumeid = $id;
        $this->uploadfor = 'resumefiles';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jsjobs_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        $filename = '';
        $return = true;
        $maxfiles = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('document_max_files');
        $query = "SELECT COUNT(id) FROM `" . jsjobs::$_db->prefix . "js_job_resumefiles` WHERE resumeid = $id";
        $totalfiles = jsjobs::$_db->get_var($query);
        foreach($_FILES['resumefiles']['name'] AS $key => $value){
            if ($maxfiles > $totalfiles) {
                if($_FILES['resumefiles']['size'][$key] > 0){
                    $file = array(
                            'name'     => sanitize_file_name($_FILES['resumefiles']['name'][$key]),
                            'type'     => sanitize_mime_type($_FILES['resumefiles']['type'][$key]),
                            'tmp_name' => sanitize_mime_type($_FILES['resumefiles']['tmp_name'][$key]),
                            'error'    => sanitize_key($_FILES['resumefiles']['error'][$key]),
                            'size'     => sanitize_key($_FILES['resumefiles']['size'][$key])
                            );
                    $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['resumefiles']['name'][$key]));
                    if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
                        $document_file_types = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('document_file_type');
                        if(jsjobslib::jsjobs_strstr($document_file_types, $filetyperesult['ext'])){
                            $result = wp_handle_upload($file, array('test_form' => false));
                            if ( $result && ! isset( $result['error'] ) ) {
                                $filename = jsjobslib::jsjobs_basename( $result['file'] );
                                $row = JSJOBSincluder::getJSTable('resumefile');
                                $cols = array();
                                $cols['id'] = '';
                                $cols['resumeid'] = $id;
                                $cols['filename'] = $filename;
                                $cols['filetype'] = $file['type'];
                                $cols['filesize'] = $file['size'];
                                $cols['created'] = date('Y-m-d H:i:s');
                                $row->bind($cols);
                                $row->store();
                                $totalfiles++; //increment file has been uploaded
                            } else {
                                /**
                                 * Error generated by _wp_handle_upload()
                                 * @see _wp_handle_upload() in wp-admin/includes/file.php
                                 */
								JSJOBSMessages::setLayoutMessage($result['error'], 'error','resume');
                            }
                        }
                    }else{
                        $return = 6;
                    }
                }
            }
        }

             // index code
            $datadirectory = JSJOBSincluder::getJSModel('configuration')->getConfigurationByConfigName('data_directory');
            $dir = wp_upload_dir();
            $file = @fopen($dir['basedir'].'/'.$path."/jobseeker/resume_".$id."/photo/index.html", 'w');
            if($file){
                fclose($file);
            }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jsjobs_upload_dir'));
        return $return;
    }
}
?>
