<?php  

defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

ini_set('upload_max_filesize', '200M');
ini_set('post_max_size', '200M');
ini_set('max_input_time', 600);
ini_set('max_execution_time', 600);

class Fileend extends CI_Controller{

    public function __construct(){
        parent::__construct();
        $this->load->model('Folder', 'folder_model');
        $this->load->model('FileModel', 'file_model');
    }
    

    public function get($id=Null){
        $partnerlist=$this->folder_model->getBannerAll();
        echo  '1';
        print_r($partnerlist);
    }

    public function add(){
       
            // $request= new Request();
            // $admin=$request->getBody();

            // 'inputadminname':$('#inputadminname').val(),
            //     'inputloginname':$('#inputloginname').val(),
            //     'inputPassword'
            // $name=$this->input->post('name');
            
            //add security trim input-todo
            //hash password for security
            // $inputflodername=$this->input->post('inputflodername');


            // $data= array(
            //     'inputflodername'=>$inputflodername,

            // );

            // $code="";
            // // if($this->frontenduser_model->admin_exists($inputadminname)==false){
            // //     $code="FAILURE";
            // //     $msg="已有管理員姓名".$inputadminname;
            // // }
            // // else
            // if($this->folder_model->folder_exists(strtolower($inputflodername))==false){
            //     $code="FAILURE";
            //     $msg="已有分類名稱".$inputflodername;
            // }
            // else{
            //     $result=$this->folder_model->insertFolder($data);
            //     if($result==false){
            //         $code="FAILURE";
            //         $msg="分類不能加入";     
            //     }
            //     else{
            //         $code="SUCCESS";
            //         $msg="分類成功加入";    
            //     }
            // }
            $label="";
            if ($_POST["label"]) {
                    $label = $_POST["label"];
            }
            //multiple file upload
             $j = 0; //Variable for indexing uploaded image 
            // $allowedExts = array("gif", "jpeg", "jpg", "png");
            $allowedExts = array("PDF", "pdf", "MP4", "mp4", "ODT", "odt", "ODP", "odp","ppt","PPT");
            $msg="";
            $code="SUCCESS";
            for ($i=0; $i < count($_FILES['file']['name']) ; $i++) { 
                $passCheck=true;

                if($this->file_model->filename_exists(strtolower($_FILES['file']['name'][$i]))==false){
                    $code="FAILURE";
                     $msg=$msg."已有相同檔案名稱".$_FILES['file']['name'][$i]."<br>";
                     $passCheck=false;
                }
                //File Size Checking
                // if($_FILES["file"]["size"][$i] < 1000000){//Approx. 1MB 
                //      $code="FAILURE";
                //      $msg=$msg."檔案大細超出限制".$_FILES['file']['name']."<br>";
                //      $passCheck=false;
                // }//if($_FILES["file"]["size"][$i] < 1000000){//Approx. 1MB 

                //End File Size Checking

                // File tyle Checking
                  $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
                    $file_extension = end($ext); //store extensions in the variable
                if(in_array($file_extension, $allowedExts)==false){
                  
                    $code="FAILURE";
                     $msg=$msg."檔案不是附合種類:".$_FILES['file']['name']."<br>";
                    $passCheck=false;
                //      $passCheck=false;
                }

                //End File  tyle Checking

                if( $passCheck==true){
                    $target_path = "upload/";
                    $newfilename=md5(uniqid()) . "." . $ext[count($ext) - 1];
                    // $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
                    $target_path = $target_path . $newfilename;//set the target path with a new name of image
                    $j = $j + 1;//increment the number of uploaded images according to the files in array 

                    if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                        // $msg=$msg.$j. ').<span id="noerror">'.$_FILES['file']['name'][$i].' uploaded successfully!.</span><br/><br/>';
                        //Insert File Name to File Name 
                         $data= array(
                            'displayname'=>$_FILES['file']['name'][$i],

                            'name'=>$newfilename,
                            'filetype'=>$file_extension,
                        );
                        $result=$this->file_model->insertFile($data);
                        if($result==false){
                            $code="FAILURE";
                            $msg=$msg."檔案".$_FILES['file']['name'][$i]."不能加入";     
                        }
                        else{
                            $code="SUCCESS";
                            $msg=$msg."檔案".$_FILES['file']['name'][$i]."成功加入";   
                        }
                        //End Insert File Name to File Name 

                    } else {//if file was not moved.
                        // echo $j. ').<span id="error">please try again!.</span><br/><br/>';
                        $msg=$msg.$j. ').<span id="error">please try again!.</span><br/><br/>';
                    }
                }//if( $passCheck==true){

                
                // $target_path = "upload/";
                // $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
                // $j = $j + 1;//increment the number of uploaded images according to the files in array  

                // if (($_FILES["file"]["size"][$i] < 1000000) //Approx. 1MB files can be uploaded.
                // && in_array($file_extension, $allowedExts)) {
                //     if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                //         echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
                //         //Insert File Name to File Name 


                //         //End Insert File Name to File Name 

                //     } else {//if file was not moved.
                //         echo $j. ').<span id="error">please try again!.</span><br/><br/>';
                //     }
                // } else {//if file size and file type was incorrect.
                //     echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
                // }
            } //for ($i=0; $i < count($_FILES['file']['name']) ; $i++) {     
   

            // foreach ($_FILES['file'] as $files) 
            // {

            //     echo $files['name'];
            //      $temp = explode(".", $files['name']);
            //      $extension = end($temp);
            //       echo $files["type"];
            //     // $temp=$target;
            //     // $tmp=$_FILES['file']['tmp_name'][$count];
            //     // $count=$count + 1;
            //     // $temp=$temp.basename($filename);
            //     // move_uploaded_file($tmp,$temp);
            //     // $temp='';
            //     // $tmp='';

            //       if ((($file["type"] == "image/gif")
            //         || ($file["type"] == "image/jpeg")
            //         || ($file["type"] == "image/jpg")
            //         || ($file["type"] == "image/pjpeg")
            //         || ($file["type"] == "image/x-png")
            //         || ($file["type"]== "image/png"))
            //         && ($file["type"] < 200000)
            //         && in_array($extension, $allowedExts)) {
            //             if ($file["error"] > 0) {
            //                 echo "Return Code: " . $file["error"] . "<br>";
            //             } else {
            //                 $filename = $label.$file["name"];
            //                 echo "Upload: " . $file["name"] . "<br>";
            //                 echo "Type: " . $file["type"] . "<br>";
            //                 echo "Size: " . ($file["size"] / 1024) . " kB<br>";
            //                 echo "Temp file: " . $file["tmp_name"] . "<br>";

            //                 if (file_exists("upload/" . $filename)) {
            //                     echo $filename . " already exists. ";
            //                 } else {
            //                     move_uploaded_file($_FILES["file"]["tmp_name"],
            //                     "upload/" . $filename);
            //                     echo "Stored in: " . "upload/" . $filename;
            //                 }
            //             }
            //         } else {
            //             echo "Invalid file";
            //         }
            // }
            //end multiple file upload
        // $allowedExts = array("gif", "jpeg", "jpg", "png");
        // $temp = explode(".", $_FILES["file"]["name"]);
        // $extension = end($temp);
        // echo $_FILES["file"]["type"];
        // if ((($_FILES["file"]["type"] == "image/gif")
        // || ($_FILES["file"]["type"] == "image/jpeg")
        // || ($_FILES["file"]["type"] == "image/jpg")
        // || ($_FILES["file"]["type"] == "image/pjpeg")
        // || ($_FILES["file"]["type"] == "image/x-png")
        // || ($_FILES["file"]["type"] == "image/png"))
        // && ($_FILES["file"]["size"] < 200000)
        // && in_array($extension, $allowedExts)) {
        //     if ($_FILES["file"]["error"] > 0) {
        //         echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        //     } else {
        //         $filename = $label.$_FILES["file"]["name"];
        //         echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        //         echo "Type: " . $_FILES["file"]["type"] . "<br>";
        //         echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        //         echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        //         if (file_exists("upload/" . $filename)) {
        //             echo $filename . " already exists. ";
        //         } else {
        //             move_uploaded_file($_FILES["file"]["tmp_name"],
        //             "upload/" . $filename);
        //             echo "Stored in: " . "upload/" . $filename;
        //         }
        //     }
        // } else {
        //     echo "Invalid file";
        // }

             
            
        //     $code="success";
        //     $msg="112";

        //      header('Content-Type: application/json');
        //     // $code="SUCCESS";
        //     // $code="FAILURE";
        //     // $msg="已有相關記錄";
        //     // $myArray = ['id'=>12, 'name'=>'Topi'];
            $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
            echo json_encode($myArray);
        //     // echo "posted";
        
    }
    public function getlevel2select(){    
             $level1id=$this->input->post('level1id');
             $result=$this->folder_model->getlevel1data($level1id);
             echo json_encode($result);
    }

     public function getlevel3select(){    
             $level2id=$this->input->post('level2id');
             $result=$this->folder_model->getlevel2data($level2id);
             echo json_encode($result);
    }
    public function getlevel4select(){    
             $level3id=$this->input->post('level3id');
             $result=$this->folder_model->getlevel3data($level3id);
             echo json_encode($result);
    }

    public function updatedir(){
         $records=$this->input->post('records');
         foreach ($records as $recordsdetail) {


                $data= array(

                'level1'=>$recordsdetail['level1'],
                'level2'=>$recordsdetail['level2'],
                'level3'=>$recordsdetail['level3'],
                // 'inputadminname'=>$inputadminname,
                'level4'=>$recordsdetail['level4'],
                'id'=>$recordsdetail['dirid']
            );
            //checking id exist or not
            

            //end checking id exist or not
                $result=$this->file_model->updatedir($data);
                if($result==false){
                    $code="FAILURE";
                    $msg="記錄不能更改";     
                }
                else{
                    $code="SUCCESS";
                    $msg="記錄成功更改";    
                }


         }//foreach ($records as $recordsdetail) {

        header('Content-Type: application/json');
        // $code="SUCCESS";
        // $code="FAILURE";
        // $msg="已有相關記錄";
        // $myArray = ['id'=>12, 'name'=>'Topi'];
        $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        echo json_encode($myArray);
        // echo "posted";
    }
    
    //File end
    public function addmore(){
        $inputflodernamelevel=$this->input->post('inputflodernamelevel');
        $addlevelid=$this->input->post('addlevelid');
        $addlevel=$this->input->post('addlevel');
        $inputboxvalue=$this->input->post('inputboxvalue');
        $inputcheckboxvalue=$this->input->post('inputcheckboxvalue');
        

        $msg="";
        foreach ($inputboxvalue as $key => $values){
            
        $data= array(
            'inputflodername'=>$values,
            'addlevelid'=>$addlevelid,
            'addlevel'=>$addlevel,
        );

            if($addlevel==1){
                if($this->folder_model->folder_levelOneexists(strtolower($values))==false){
                    $code="FAILURE";
                    $msg=$msg."已有分類名稱".$values."<br>";
                }
                else{
                    $result=$this->folder_model->insertLevelOneFolder($values,$addlevel);
                    if($result==false){
                        $code="FAILURE";
                        $msg=$msg."分類不能加入"."<br>";    
                    }
                    else{
                        $code="SUCCESS";
                        $msg=$msg."分類成功加入"."<br>";    
                    }
                }   
            }//if($addlevel==1){

            if($addlevel==2){ 
                if($this->folder_model->folder_levelTwoexists(strtolower($values),$addlevel,$addlevelid)==false){
                    $code="FAILURE";
                    $msg=$msg."已有分類名稱".$values."<br>";
                }
                else{
                    $result=$this->folder_model->insertLevelTwoFolder($values,$addlevel,$addlevelid);
                    if($result==false){
                        $code="FAILURE";
                        $msg=$msg."分類不能加入"."<br>";    
                    }
                    else{
                        $code="SUCCESS";
                        $msg=$msg."分類成功加入"."<br>";    
                    }
                }
            }//if($addlevel==2){   

            if($addlevel==3){
                foreach ($inputcheckboxvalue as $secondkey => $secondvalues){
                    if($this->folder_model->folder_levelThreeexists(strtolower($values),$addlevel,$addlevelid,$secondvalues)==false){
                        $code="FAILURE";
                        $msg=$msg."已有分類名稱".$values."<br>";
                    }
                    else{
                        $result=$this->folder_model->insertLevelThreeFolder($values,$addlevel,$addlevelid,$secondvalues);
                        if($result==false){
                            $code="FAILURE";
                            $msg=$msg."分類不能加入"."<br>";    
                        }
                        else{
                            $code="SUCCESS";
                            $msg=$msg."分類成功加入"."<br>";    
                        }
                    }

                }//foreach ($inputcheckboxvalue as $secondkey => $secondvalues){
            }//if($addlevel==3){    
                
            if($addlevel==4){
                foreach ($inputcheckboxvalue as $thirdkey => $thirdvalues){
                    if($this->folder_model->folder_levelFourexists(strtolower($values),$addlevel,$addlevelid,$thirdvalues)==false){
                        $code="FAILURE";
                        $msg=$msg."已有分類名稱".$values."<br>";
                    }
                    elseif($this->folder_model->checklevelthreeid($thirdvalues)){
                        $code="FAILURE";
                        $msg=$msg."所選不是第三分類".$values."<br>";
                    }
                    else{
                        $result=$this->folder_model->insertLevelFourFolder($values,$addlevel,$addlevelid,$thirdvalues);
                        if($result==false){
                            $code="FAILURE";
                            $msg=$msg."分類不能加入"."<br>";    
                        }
                        else{
                            $code="SUCCESS";
                            $msg=$msg."分類成功加入"."<br>";    
                        }
                    }

                }//foreach ($inputcheckboxvalue as $secondkey => $secondvalues){
            }//if($addlevel==4){
            if($addlevel==24){
                //add 12months and 5 weeks
                foreach ($inputcheckboxvalue as $secondkey => $secondvalues){
                    // if($this->folder_model->folder_levelTwoMonthWeekexists(strtolower($values),$addlevel,$addlevelid,$secondvalues)==false){
                    //     $code="FAILURE";
                    //     $msg=$msg."已有分類名稱".$values."<br>";
                    // }
                    // else
                    if($this->folder_model->checkleveltwoid($secondvalues)){
                        $code="FAILURE";
                        $msg=$msg."所選不是第二分類".$values."<br>";
                    }
                    else{
                        $result=$this->folder_model->insertLevelMonthWeekFolder($values,$addlevel,$addlevelid,$secondvalues);
                        if($result==false){
                            $code="FAILURE";
                            $msg=$msg."分類不能加入"."<br>";    
                        }
                        else{
                            $code="SUCCESS";
                            $msg=$msg."分類成功加入"."<br>";    
                        }
                    }

                }//foreach ($inputcheckboxvalue as $secondkey => $secondvalues){
                //end add 12months ans 5 weeks
            }//if($addlevel==24){

        // $code="";
        // // if($this->frontenduser_model->admin_exists($inputadminname)==false){
        // //     $code="FAILURE";
        // //     $msg="已有管理員姓名".$inputadminname;
        // // }
        // // else
        // if($this->folder_model->folder_exists(strtolower($inputflodernamelevel))==false){
        //     $code="FAILURE";
        //     $msg=$msg."已有分類名稱".$inputflodernamelevel."<br>";
        // }
        // else{
        //     $result=$this->folder_model->insertLevelFolder($data);
        //     if($result==false){
        //         $code="FAILURE";
        //         $msg=$msg."分類不能加入"."<br>";    
        //     }
        //     else{
        //         $code="SUCCESS";
        //         $msg=$msg."分類成功加入"."<br>";    
        //     }
        // }

        }// foreach ($inputflodernamelevel as $key => $values){
        

         header('Content-Type: application/json');
        // $code="SUCCESS";
        // $code="FAILURE";
        // $msg="已有相關記錄";
        // $myArray = ['id'=>12, 'name'=>'Topi'];
        $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        echo json_encode($myArray);
        // echo "posted";
    }
    public function edit(){
       
        // $request= new Request();
        // $admin=$request->getBody();

        // 'inputadminname':$('#inputadminname').val(),
        //     'inputloginname':$('#inputloginname').val(),
        //     'inputPassword'
        // $name=$this->input->post('name');
        
        //add security trim input-todo
        //hash password for security
        $inputcompanynameedit=$this->input->post('inputcompanynameedit');
        $inputfullnameedit=$this->input->post('inputfullnameedit');
        $inputteledit=$this->input->post('inputteledit');
        // $inputadminname=$this->input->post('inputadminnameedit');
        $inputloginname=$this->input->post('inputloginnameedit');
        $inputPassword=$this->input->post('inputPasswordedit');
        $id=$this->input->post('inputadminid');

        $data= array(

            'inputcompanynameedit'=>$inputcompanynameedit,
            'inputfullnameedit'=>$inputfullnameedit,
            'inputteledit'=>$inputteledit,
            // 'inputadminname'=>$inputadminname,
            'inputloginname'=>$inputloginname,
            'inputPassword'=>$inputPassword,
            'id'=>$id
        );

        $code="";
        // if($this->frontenduser_model->admin_existsbyid($inputadminname,$id)==false){
        //     $code="FAILURE";
        //     $msg="已有管理員姓名".$inputadminname;
        // }
        // else
        if($this->frontenduser_model->login_existsbyid(strtolower($inputloginname),$id)==false){
            $code="FAILURE";
            $msg="已有登入名稱".$inputloginname;
        }
        else{
            $result=$this->frontenduser_model->updateAdmin($data);
            if($result==false){
                $code="FAILURE";
                $msg="記錄不能更改";     
            }
            else{
                $code="SUCCESS";
                $msg="記錄成功更改";    
            }

            
        }

         
        

         header('Content-Type: application/json');
        // $code="SUCCESS";
        // $code="FAILURE";
        // $msg="已有相關記錄";
        // $myArray = ['id'=>12, 'name'=>'Topi'];
        $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        echo json_encode($myArray);
        // echo "posted";
    
    }
    public function delete(){
        $inputdeletecheckboxvalue=$this->input->post('inputdeletecheckboxvalue');
        $result=true;
        foreach ($inputdeletecheckboxvalue as $key => $values){
            // if($this->file_model->deleteFile($values)==false){
            //     $result=false; 
            // }
            // $this->config->load('constants', true);
            // echo $this->file_model->deleteFile($values );
            if($this->file_model->deleteFile($values)==false){
                $result=false; 
            }
        }//foreach ($inputdeletecheckboxvalue as $key => $values){
    
        if($result==true){
            $code="SUCCESS";
            $msg="相關記錄成功删徐";
        }
        else{
            $code="FAILURE";
            $msg="相關記錄不能删徐";
        }
       
        // $msg=$inputdeletecheckboxvalue;
        // header('Content-Type: application/json');
        // $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        // echo json_encode($myArray);
    }
    public function getadmindata(){
        $id=$this->input->post('user_id');
        $data=$this->frontenduser_model->getAdmindateByid($id);
        header('Content-Type: application/json');
        echo json_encode($data);
    }

}//class Admins {
