<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Auth\DefaultPasswordHasher;
use DateTimeZone;
/**
 * Users Controller
 *
 * @property \App\Model\Table\UsersTable $Users
 */
require_once(ROOT . DS  .'vendor' . DS  . 'S3.php');


class UsersController 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;

            if(isset($this->request->data['search']) && $this->request->data['search']!=''){
                $searchData['search'] = $this->request->data['search'];
                $newCondition['Users.username like'] = '%'.trim($this->request->data['search']).'%'; 
                $newCondition['Users.display_name like'] = '%'.trim($this->request->data['search']).'%'; 
                $newCondition['Users.email like'] = '%'.trim($this->request->data['search']).'%';
                $condition['OR'] = @$newCondition;              
            }
           
            $users = $this->Users->find('all')->where($condition)->toArray();
           
        }else{            
            $users = $this->paginate($this->Users);          
        }
        //pr($users);exit;

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

    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);

        $this->set('user', $user);
        $this->set('_serialize', ['user']);
    }

    
    public function add()
    {
        $timezone = DateTimeZone::listIdentifiers(DateTimeZone::ALL);

        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
        // print_r($this->request->data['mobile']);die;
        // $this->request->data['username'];
        // $this->request->data['password']=1234;
        // $this->request->data['display_name'];
        // $this->request->data['status'];
        // $this->request->data['role'];
        // $this->request->data['email'];
        // $this->request->data['profile_img']='RAM';
        // $this->request->data['default_watch'];
        // $this->request->data['mobile'];
        if(!empty($this->request->data['profile_img'])) { 
            $nameArr = [];
            $value =$this->request->data['profile_img'] ;
                $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 = 'workolics/profile_image/'.$name;
                $s3 = new \S3(awsAccessKey, awsSecretKey);
            
                $r = $s3->putObjectFile($tmp_name, bucketName, $path, \S3::ACL_PUBLIC_READ);
                $nameArr[] = $path;
            $this->request->data['profile_img'] = implode(',',$nameArr);
        }else{
           unset($this->request->data['profile_img']);
         $this->request->data['profile_img'] = '';
        }

            $user = $this->Users->patchEntity($user, $this->request->data);
        // print_r($user);
          
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));
                // die;
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
            // print_r('ORADEEO');die;
        }
        $this->set(compact('user','timezone'));
        $this->set('_serialize', ['user']);
    }

    /**
     * Edit method
     *
     * @param string|null $id User 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)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);
        $profile_img = $user['profile_img'];
        if ($this->request->is(['patch', 'post', 'put'])) {
          
            if($this->request->data['password'] == ''){
                unset($this->request->data['password']);
            }

            if(!empty($this->request->data['profile_img'])) { 
                $nameArr = [];
                $value =$this->request->data['profile_img'] ;
                    $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 = 'workolics/profile_image/'.$name;
                    $s3 = new \S3(awsAccessKey, awsSecretKey);
                
                    $r = $s3->putObjectFile($tmp_name, bucketName, $path, \S3::ACL_PUBLIC_READ);
                    $nameArr[] = $path;
                $this->request->data['profile_img'] = implode(',',$nameArr);
            }else{
               unset($this->request->data['profile_img']);
             $this->request->data['profile_img'] = '';
            }


            $user = $this->Users->patchEntity($user, $this->request->data);
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user','profile_img'));
        $this->set('_serialize', ['user']);
    }

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

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

    /**
     * Login method
     *
     * @param string|null user name & password auth login.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function login() {

        if ($this->request->is('post')) {

            $user = $this->Auth->identify();
               
            if ($user) {
                $this->Auth->setUser($user);

                return $this->redirect($this->Auth->redirectUrl());
            } else {
                $this->Flash->error(__('Username or password is incorrect'));
            }
        }

    }
    
    /**
     * dashboard method
     *
     * @param string|null user name & password auth login.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function dashboard(){
        $this->loadModel('Projects');
        $this->loadModel('Freelancers');
        $this->loadModel('Bids');
        $this->loadModel('Transactions');
        $this->loadModel('Orders');
       // $projects =  $this->Projects->find('all')->select(['Projects.id','Projects.order_status'])->toArray();
        $prjectData = $this->Projects->find('all');
        $prjectData->select([ 
                      'order_status',
                      'count' => $prjectData->func()->count('*')
                     ])            
                    ->group('order_status');
        $project_count = array();
        $total_project = 0;
        foreach ($prjectData as $row) {
           $order_status = $row['order_status'];
           $project_count[$order_status] = $row['count'];
           $total_project+=$row['count'];
        }
        
        $freelancData = $this->Freelancers->find('all');
        $freelancData->select([ 
                      'status',
                      'count' => $freelancData->func()->count('*')
                    ])            
                     ->group('status');
        $freelanc_count = array();
        $total_freelancer = 0;
        foreach ($freelancData as $row) {
           $status = $row['status'];
           $freelanc_count[$status] = $row['count'];
           $total_freelancer+= $row['count'];
        }
        
       
        $bidsData = $this->Bids->find('all');
        $bidsData->select([ 
                      'allotment_status',
                      'count' => $bidsData->func()->count('*')
                    ])            
                 ->group('allotment_status');
        $bids_count = array();
        $total_bids = 0;
        foreach ($bidsData as $row) {
           $status = $row['allotment_status'];
           $bids_count[$status] = $row['count'];
           $total_bids+= $row['count'];
        }
        
        $OrderData = $this->Orders->find('all');
        $OrderData->select([ 
                      'submission_status',
                      'count' => $OrderData->func()->count('*')
                    ])            
                 ->group('submission_status');
        $order_count = array();
        $total_orders = 0;  
        foreach ($OrderData as $row) {
           $status = $row['submission_status'];
           $order_count[$status] = $row['count'];
           $total_orders+= $row['count'];
        }    
       

        $query = $this->Transactions->find();
        $transactions = $query->select(['total' => $query->func()->sum('pay_amount')])->toArray();
        

        $allData = array();
        $allData['total_projects'] = @$total_project;
        $allData['complete_projects'] = @$project_count[1];
        $allData['cancelled_projects'] = @$project_count[3];
        $allData['pending_projects'] = @$project_count[0];

        $allData['total_freelancer'] = @$total_freelancer;
        $allData['active_freelancer'] = @$freelanc_count[1];
        $allData['inactive_freelancer'] = @$freelanc_count[0];

        $allData['total_bids'] = @$total_bids;
        $allData['alloted_bids'] = @$bids_count[1];
        $allData['pending_bids'] = @$bids_count[0]; 

        $allData['total_orders'] = @$total_orders;
        $allData['pending_orders'] = @$order_count[0];
        $allData['complete_orders'] = @$order_count[0];

        $allData['transactions'] = $transactions;
        //pr($allData);exit;
        $this->set(compact('allData'));

       

    }
    public function logout() {
        return $this->redirect($this->Auth->logout());
  // $this->redirect('http://auth0.domain?returnTo=http://example.com/');
    }
    public function projects(){
        $this->loadModel('Projects');
        $projects = $this->Projects->find('all')->toArray();
        $this->set(compact('projects'));
    }
    public function cancelled(){
        $this->loadModel('Projects');
        $projects = $this->Projects->findByOrderStatus('3')->toArray();        
        $this->set(compact('projects'));       
        $this->render("projects");
    }
    public function deadlineProjects(){
        $startDate = date("Y-m-d", strtotime("-4 day"));
        $endDate =  date("Y-m-d", strtotime("+4 day"));
       
        $this->loadModel('Projects');
        $projectsData = $this->Projects->find('all',[
                        'conditions' => [
                                 'and' => array(
                                array('Projects.deadline_date <= ' => $endDate,
                                      'Projects.deadline_date >= ' => $startDate
                                ),                                
                                'Projects.order_status =' => '0'
                                )
                        ]
                    ]);
                   

     
      $projects = $projectsData->toArray();
       $this->set(compact('projects')); 
      
    } 
    public function notauthenticate(){
            
    }
}
