<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Illuminate\Support\Str;

/**
 * Orders Controller
 *
 * @property \App\Model\Table\OrdersTable $Orders
     */

 require_once(ROOT . DS  .'vendor' . DS  . 'S3.php');

class OrdersController 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;
           // pr($this->request->data);exit;
            if(isset($this->request->data['search']) && $this->request->data['search']!=''){
                $searchData['search'] = $this->request->data['search'];
                $newCondition['Projects.topic like'] = '%'.$this->request->data['search'].'%';
                $newCondition['Freelancers.name like'] = '%'.$this->request->data['search'].'%';               
                $condition['OR'] = $newCondition;
            } 
            if(isset($this->request->data['pay_status']) && $this->request->data['pay_status']!=''){
                $searchData['pay_status'] = $this->request->data['pay_status'];
                $condition['Orders.pay_status'] = $this->request->data['pay_status'];
            }
            if(isset($this->request->data['datefilter']) && $this->request->data['datefilter']!=''){
                $datefilter = explode('-', $this->request->data['datefilter']);
                $startDate = date('Y-m-d',strtotime($datefilter[0]));
                $endDate = date('Y-m-d',strtotime($datefilter[1]));
                $condition['Orders.submission_date <='] = $endDate;
                $condition['Orders.submission_date >='] = $startDate;
               // $conditions['LogfileRecord.date BETWEEN ? and ?' => array($start_date, $end_date)];
                
            }
            
          //pr($condition);exit;
            $orders = $this->Orders->find('all')->contain(['Projects', 'Freelancers'])->where($condition)->toArray();
           
        }else{            
            $this->paginate = ['contain' => ['Freelancers','Projects'],'order'=>['id'=>'desc']];
            $orders = $this->paginate($this->Orders);
        }

        

//  print_r( $orders->toArray());die;
        $this->set(compact('orders','filter','searchData'));
        $this->set('_serialize', ['orders']);
    }

    /**
     * View method
     *
     * @param string|null $id Order id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $order = $this->Orders->get($id, [
            'contain' => ['Freelancers', 'Projects', 'Chats']
        ]);
        $tracaction = $this->Orders->Transactions->find('all')->contain(['Freelancers'])->where(['Transactions.order_id'=>$id])->toArray();
        
        $this->set(compact('tracaction','order'));
        $this->set('_serialize', ['order']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|null Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $order = $this->Orders->newEntity();
        $this->loadModel('Projects');
        $projects = $this->Projects->find('all')->toArray();
        // $projects = $this->Projects->find('all')->order(['id' => 'DESC'])->toArray();
        if ($this->request->is('post')) {
            $this->request->data['submission_date']=date('Y-m-d h:i:s',strtotime( $this->request->data['submission_date']));

            if(!empty($this->request->data['attachment'])) { 
                $value =$this->request->data['attachment'] ;
                    $tmp_name = $value["tmp_name"];
                    $name = str_replace(' ','-',$value);
                    $ext = pathinfo($name, PATHINFO_EXTENSION);
                    $name = substr(pathinfo($name,PATHINFO_BASENAME),0,10).'_'.rand().'.'.$ext.'_'.strtotime(date('Y-m-d h:i:s'));
                    $path = 'project/'.$name;
                    $s3 = new \S3(awsAccessKey, awsSecretKey);
                
                    $r = $s3->putObjectFile($tmp_name, bucketName, $path, \S3::ACL_PUBLIC_READ);


                $this->request->data['attachment'] = $path;
            }else{
               unset($this->request->data['attachment']);
             $this->request->data['attachment'] = '';
            }


            $order = $this->Orders->patchEntity($order, $this->request->data);
            // print_r($this->request->data);die;
            if ($this->Orders->save($order)) {

                $this->Flash->success(__('The order has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The order could not be saved. Please, try again.'));
        }
        $freelancers = $this->Orders->Freelancers->find('list', ['limit' => 200]);
        $this->set(compact('order', 'freelancers','projects'));
        $this->set('_serialize', ['order']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Order id.
     * @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)
    {
        $order = $this->Orders->get($id, [
            'contain' => []
        ]);
        $this->loadModel('Projects');
        $projects = $this->Projects->find('all')->toArray();
        if ($this->request->is(['patch', 'post', 'put'])) {
            $this->request->data['submission_date']=date('Y-m-d h:i:s',strtotime( $this->request->data['submission_date']));
            if(!empty($this->request->data['attachment'])) { 
                $value =$this->request->data['attachment'] ;
                    $tmp_name = $value["tmp_name"];
                    $name = str_replace(' ','-',$value);
                    $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);


                $this->request->data['attachment'] = $path;
            }else{
               unset($this->request->data['attachment']);
             $this->request->data['attachment'] = '';
            }
            $order = $this->Orders->patchEntity($order, $this->request->data);
            if ($this->Orders->save($order)) {
                $this->Flash->success(__('The order has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The order could not be saved. Please, try again.'));
        }
        $freelancers = $this->Orders->Freelancers->find('list', ['limit' => 200]);
        $this->set(compact('order', 'freelancers','projects'));
        $this->set('_serialize', ['order']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Order 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']);
        $order = $this->Orders->get($id);
        if ($this->Orders->delete($order)) {
            $this->Flash->success(__('The order has been deleted.'));
        } else {
            $this->Flash->error(__('The order could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}
