<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;

use Cake\Mailer\Email;

// use App\Controller\S3;
 //The following line should do the same like App::import() in the older version of cakePHP
 require_once(ROOT . DS  .'vendor' . DS  . 'S3.php');


/**
 * Projects Controller
 *
 * @property \App\Model\Table\ProjectsTable $Projects
 */
class ProjectsController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $filter =0;$searchData=array();$condition = array();
        if ($this->request->is('post')) {
            $filter =1;
            $searchData['search']=$this->request->data['search'];
            if(isset($this->request->data['search']) && $this->request->data['search']!=''){
                $searchData['course_name'] = $this->request->data['search'];
                $newCondition['topic like'] = '%'.trim($this->request->data['search']).'%';
                $newCondition['subject like'] = '%'.trim($this->request->data['search']).'%';
                // $newCondition['order_id like'] = '%'.trim($this->request->data['search']).'%';
                $condition['OR'] = $newCondition;
            }
            $projects = $this->Projects->find('all')->contain(['Bids'])->where($condition)->order(['id' => 'DESC'])->toArray();
          
        }else{            
            $this->paginate = [ 'contain' => ['Bids'],'order'=>['id'=>'desc']];
            $projects = $this->paginate($this->Projects);
        }

        $this->set(compact('projects','filter','searchData'));
        $this->set('_serialize', ['projects']);
    }

    /**
     * View method
     *
     * @param string|null $id Project id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $project = $this->Projects->get($id, [
            'contain' => ['Orders', 'Bids']
        ]);
         
        $Freelancers = TableRegistry::get('Freelancers');
         $bids = TableRegistry::get("Bids");  
        if(@$project->orders[0]){
            $project->freelancer = $Freelancers->findById($project->orders[0]['freelancer_id'])->first();
        }
        
        $project->bids =  $bids->find('all')->select(['Freelancers.name','Bids.freelancer_id','Bids.allotment_status','Bids.created','Bids.id'])->contain(['Freelancers'])->where(['project_id' => $id])->toArray();

        $s3url =  $this->viewVars['s3url'];

        $subjects = TableRegistry::get('Subjects')->find('list')->where(['status'=>1])->toArray();
        $this->set(compact('project','s3url','subjects'));
        $this->set('_serialize', ['project']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|null Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $project = $this->Projects->newEntity();
        if ($this->request->is('post')) {

            // if(!empty($this->request->data['file_data']['name'])) {

            //     $file = $this->request->data['file_data']['name']; 
            //     $name= strtotime(date('d-m-Y h:i:s')).'_'.$file;
            //     $dir =  'img/Projects/'; 
            //     $tmp_name= $this->request->data['file_data']['tmp_name'];
            // //    pr(strtotime(date('d-m-Y h:i:s')).'_'.$file);exit;
            //     // if(move_uploaded_file($this->request->data['file_data']['tmp_name'], $dir . $file))  { 
            //     //     $this->request->data['file_data'] = $name;
            //     // }else{
            //     //     echo "not";exit;
            //     // }
            //     // $this->request->data['file_data'] = $file;
            //     // $path = 'workolics/project/'.$file;
            //     // $s3 = new \S3(awsAccessKey, awsSecretKey);
                
            //     // $r = $s3->putObjectFile($tmp_name, bucketName, $path, \S3::ACL_PUBLIC_READ);

            // }

            // echo awsSecretKey;die;
            // pr($this->request->data ); die;
//             if(!empty($this->request->data['file_data']['name'])) {
//                 $nameArr = [];
//                 foreach ($this->request->data['file_data'] as $key => $value) {
//                     $tmp_name = $value["tmp_name"];
//                     $name = str_replace(' ','-',$value["name"]);
//                     // $ext = pathinfo($name, PATHINFO_EXTENSION);
//                     // $name = substr(pathinfo($name,PATHINFO_BASENAME),0,10).'_'.rand().'.'.$ext;
// pr($this->request->data['file_data'] );die;
//                     $path = 'workolics/project/'.$name;
//                     if($this->request->data['website'] != ''){
//                         $path = $this->request->data['website'].'/'.$name;
//                     }
//                     // die;
//                     $s3 = new \S3(awsAccessKey, awsSecretKey);
                
//                     $r = $s3->putObjectFile($tmp_name, bucketName, $path, \S3::ACL_PUBLIC_READ);
//                     $nameArr[] = $path;
//                 }
//                 // $return = array('result' => $r,'name' => $name);
//                 // print_r($path); die;
//                 $this->request->data['file_data'] = implode('?|@$',$nameArr);
//             }

            // pr($_FILES);
            // exit;

            
            if(!empty($this->request->data['file_data']['name'])) {
                $nameArr = [];
                $value =$this->request->data['file_data'] ;
                // foreach ($this->request->data['file_data'] as $key => $value) {
                    $tmp_name = $value["tmp_name"];
                    $name = str_replace(' ','-',$value["name"]);
                    $ext = pathinfo($name, PATHINFO_EXTENSION);
                    $name = substr(pathinfo($name,PATHINFO_BASENAME),0,10).'_'.rand().'.'.$ext;

                    $path = 'project/'.$name;
                    $s3 = new \S3(awsAccessKey, awsSecretKey);
                
                    $r = $s3->putObjectFile($tmp_name, bucketName, $path, \S3::ACL_PUBLIC_READ);
                    $nameArr[] = $path;
                // }
                // $return = array('result' => $r,'name' => $name);
                $this->request->data['file_data'] = implode(',',$nameArr);
            }else{
               unset($this->request->data['file_data']);
             $this->request->data['file_data'] = '';
            }
            
            $this->request->data['deadline_date'] = date('Y-m-d H:i:s',strtotime($this->request->data['deadline_date']));
            $this->request->data['bid_expiry_date'] = date('Y-m-d H:i:s',strtotime($this->request->data['bid_expiry_date']));
            $project = $this->Projects->patchEntity($project,$this->request->data);
            
            if ($this->Projects->save($project)) {
                $this->Flash->success(__('The project has been saved.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The project could not be saved. Please, try again.'));
        }

        $subjects = TableRegistry::get('Subjects')->find('list')->where(['status'=>1])->toArray();
        $this->set(compact('project','subjects'));
        $this->set('_serialize', ['project']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Project id._accessible
     * @return \Cake\Network\Response|null Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $project = $this->Projects->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $this->request->data['filedirectory'] = 'project';
            $this->request->data['deadline_date'] = date('y-m-d h:i:s',strtotime($this->request->data['deadline_date']));
            // pr($this->request->data['file_data']); die;
            if(!empty($this->request->data['file_data'][0]['name'])) {
                $nameArr = [];
                foreach ($this->request->data['file_data'] as $key => $value) {
                    $tmp_name = $value["tmp_name"];
                    $name = str_replace(' ','-',$value["name"]);
                    $ext = pathinfo($name, PATHINFO_EXTENSION);
                    $name = substr(pathinfo($name,PATHINFO_BASENAME),0,10).'_'.rand().'.'.$ext;

                    $path = 'project/'.$name;
                    if($this->request->data['website'] != ''){
                        $path = $this->request->data['website'].'/'.$name;
                    }
                    $s3 = new \S3(awsAccessKey, awsSecretKey);
                
                    $r = $s3->putObjectFile($tmp_name, bucketName, $path, \S3::ACL_PUBLIC_READ);
                    $nameArr[] = $path;
                }
                // $return = array('result' => $r,'name' => $name);
                $this->request->data['file_data'] = implode('?|@$',$nameArr);
            }else{
                //$this->request->data['file_data'] = '';
                unset($this->request->data['file_data']);
            }
            
            $this->request->data['deadline_date'] = date('Y-m-d H:i:s',strtotime($this->request->data['deadline_date']));
            $this->request->data['bid_expiry_date'] = date('Y-m-d H:i:s',strtotime($this->request->data['bid_expiry_date']));
            
            $project = $this->Projects->patchEntity($project, $this->request->data);
               
            if ($this->Projects->save($project)) {
                $this->Flash->success(__('The project has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The project could not be saved. Please, try again.'));
        }
        $subjects = TableRegistry::get('Subjects')->find('list')->where(['status'=>1])->toArray();
        $this->set(compact('project','subjects'));
        $this->set('_serialize', ['project']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Project id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $project = $this->Projects->get($id);
        if ($this->Projects->delete($project)) {
            $this->Flash->success(__('The project has been deleted.'));
        } else {
            $this->Flash->error(__('The project could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
    public function assignProject(){
       //  $this->viewBuilder()->layout('ajax');
        $maildata = array();
        $this->loadModel('Orders');
        $this->loadModel('Freelancers');
        if($this->request->is('post')){
            $this->request->data['submission_status'] = 0;
            //$this->request->data['submission_date'] = '0000-00-00';
            $this->request->data['attachment'] = "na";  
            $this->request->data['feedback_count'] = 0;
            $this->request->data['ratings'] = "0";
            $this->request->data['pay_status'] = "0";
            $project_id = $this->request->data['project_id'];
            $orderData = $this->Orders->find()->select('id')->where(['project_id'=>$project_id])->first();
            // echo '<pre>';print($orderData);die;
            if(@$orderData['id']){
                $newData = $this->Orders->patchEntity($orderData,$this->request->data);
                $this->Orders->save($newData);
            }else{
                $newData = $this->Orders->newEntity($this->request->data);          
                $this->Orders->save($newData);
            }
            $freelancerData = $this->Freelancers->get($this->request->data['freelancer_id']);       
            $email = new Email();
            $email->transport('mail');
            try {
                $res = $email->from(['testcognus@gmail.com' => 'Freelancer'])
                      ->viewVars(['name' => $freelancerData['name'],'project_id' => $this->request->data['project_id'],'project_name'=>$this->request->data['project_name']])
                      ->template('assignProject', 'default')
                      ->emailFormat('both')
                      ->to([$freelancerData['email'] => 'Assigned'])
                      ->subject('Project Assigned')                  
                      ->send();
            } catch (Exception $e) {
                echo 'Exception : ',  $e->getMessage(), "\n";
            }
            $this->set(compact('freelancerData'));
        }
       
    }
    public function export(){

            $filename = 'Projects-'.date('d M,Y h:i A');
            
            $results = $this->Projects->find('all')->toArray();
            
            $csv_file = fopen('php://output', 'w');
 
            header('Content-type: application/csv');
            header('Content-Disposition: attachment; filename="'.$filename.'"');
 
            $header_row = array("ID", "TOPIC", "SUBJECT","PAGES","WORDS","PRICE","WEBSITE","ADDED");
 
            fputcsv($csv_file,$header_row,',','"');
            foreach($results AS $result) {
               
                $row = array(
                $result['id'],
                $result['topic'],
                $result['subject'],
                $result['pages'],
                $result['words'],
                $result['price'],
                $result['website'],
                $result['created']
                );
                
                fputcsv($csv_file,$row,',','"');
            }
            
            fclose($csv_file);
       
       
        $this->render(false);
        exit;
        
    }
}
