<?php

namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Mailer\Email;
use Cake\Core\Configure;


/**
 * Freelancers Controller
 *
 * @property \App\Model\Table\FreelancersTable $Freelancers
 */

require_once(ROOT . DS  . 'vendor' . DS  . 'S3.php');
class FreelancersController extends AppController
{
    public function index($status = null)
    {
        $filter = 0;
        $searchData = array();
        $condition = array();
        $contain = [];
        // if (!empty($this->request->query['category'])) {
        //         $contain['CategoryToFreelancer'] = function ($q){
        //             return $q->where(['CategoryToFreelancer.category_id' => $this->request->query['category']]);
        //         };

        // }else {
        //     $contain[] = 'CategoryToFreelancer';
        // }


        if (!empty($this->request->query)) {
            // dd($this->request->query());
            // $filter = 1;
            if (!empty($this->request->query['id'])) {
                $condition['Freelancers.id'] =  trim($this->request->query['id']);
            }
            // var_dump($newCondition1); die;
            if (isset($this->request->query['search']) && $this->request->query['search'] != '') {
                $searchData['search'] = $this->request->query['search'];
                $newCondition['Freelancers.email like'] = '%' . trim($this->request->query['search']) . '%';
                $newCondition['Freelancers.mobile like'] = '%' . trim($this->request->query['search']) . '%';
                $condition['OR'] = $newCondition;
            } 
            if (isset($this->request->query['fname']) && $this->request->query['fname'] != '') {
                $newCondition['Freelancers.name like'] = '%' . trim($this->request->query['fname']) . '%';
                $condition['OR'] = $newCondition;
            }
            if (isset($this->request->query['approve']) && $this->request->query['approve'] != '') {
                if (($this->request->query['approve']) == 0) {
                    $condition['Freelancers.reg_stage !='] = 4;
                } elseif ($this->request->query['approve'] == 1) {
                    $condition['Freelancers.reg_stage'] = 4;
                } elseif ($this->request->query['approve'] == '') {
                    $condition[] = '';
                }
            }
            if (!empty($this->request->query['country'])) {
                $newCondition['Freelancers.country like'] = '%' . trim($this->request->query['country']) . '%';
                $newCondition['Freelancers.city like'] = '%' . trim($this->request->query['country']) . '%';
                $condition['OR'] = $newCondition;
            }
            // if ($this->request->query('category') > 0) {
            //     // $condition['CategoryToFreelancer.category_id'] =$this->request->query['category'];

            //     // $containModel = ['CategoryToFreelancer' => function ($q) {
            //     //     return $q->select(['freelancer_id', 'category_id']);
            //     // }];
            //     $containModel[]=['CategoryToFreelancer'=>['condition'=>['category_id'=>$this->request->query['category']]]];
            // }

            // if ($this->request->query('subject') > 0) {
            //     $condition[] ="FIND_IN_SET(".$this->request->query['subject'].",Freelancers.proficient)";
            // }
            if (isset($this->request->query['datefilter']) && $this->request->query['datefilter'] != '') {

                $date = explode('-', $this->request->query['datefilter']);
                $to = date('Y-m-d', strtotime($date[0]));
                $from =  date('Y-m-d', strtotime($date[1]));
                $condition['Freelancers.created >= '] = $to;
                $condition['Freelancers.created <= '] = $from;
                // $condition[] = $newCondition;
            }
        }
        $condition['Freelancers.delete_status '] = 0;
        // dd($contain);

        // if (!empty($this->request->query['category'])) {

        //         $condition['CategoryToFreelancer.category_id'] =$this->request->query['category'];
        // }
        $this->paginate = [
            'contain' =>  [
                'CategoryToFreelancer' => function ($q) {
                    if ($this->request->getQuery('category')) {
                        return $q->where(['CategoryToFreelancer.status' => 1]);
                    }
                    return $q;
                }
            ], 'conditions' => $condition,
            'order' => ['id' => 'desc']
        ];
        // $query = $this->Freelancers->find('all')->contain($contain);
        // echo $query->sql();die;

        // debug($this->paginate);die;
        $freelancers = $this->paginate($this->Freelancers);
        // dd($freelancers);
        $subject = TableRegistry::get('Subjects')->find('list')->where(['status' => 1])->toArray();

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



    public function view($id = null)
    {
        $freelancer = $this->Freelancers->get($id, [
            'contain' => ['Transactions', 'Projects', 'CategoryToFreelancer']
        ]);
        if ($freelancer->view == 0) {
            $fls = TableRegistry::get('Freelancers');
            $fl = $fls->get($freelancer->id);
            $fl->view = 1;
            $fls->save($fl);
        }
        // $freelancer->

        $results = TableRegistry::get('Results');
        $essayTest = TableRegistry::get("EssayTest");
        $bids = TableRegistry::get("Bids");
        $Projects = TableRegistry::get("Projects");


        $freelancer->bids =  $bids->find('all')->select(['Bids.id', 'Projects.topic', 'Bids.allotment_status', 'Bids.freelancer_id', 'Bids.project_id', 'Bids.created'])->contain(['Projects'])->where(['Bids.freelancer_id' => $id])->toArray();
        // dd($freelancer);
        $freelancer->results =  $results->find('all')->select(['Questions.question', 'Results.answer_status', 'Results.question_id'])->contain(['Questions'])->where(['freelancer_id' => $id])->toArray();
        $freelancer->essayTest = $essayTest->find()->select(['EssayTest.id', 'EssayTest.topic', 'EssayTest.essay', 'EssayTest.g_mistakes', 'EssayTest.freelancer_id', 'EssayTest.result', 'EssayTest.category_id'])->where(['freelancer_id' => $id])->toArray();
        // dd($freelancer);

        //pr($freelancer->essayTest); die;
        // echo "<pre>";print_r($freelancer);die;
        // if (!empty($freelancer['orders'])) {
        //     foreach ($freelancer['orders'] as $key => $orders) {
        //         $p_data = $Projects->find('all')->select(['Projects.topic', 'Projects.created'])->where(['Projects.id' => $orders['project_id']])->toArray();
        //         $assigned_projects[$orders['project_id']]['topic'] = $p_data[0]['topic'];
        //         $assigned_projects[$orders['project_id']]['created'] = $p_data[0]['created'];
        //         $assigned_projects[$orders['project_id']]['sub_status'] = $orders['submission_status'];
        //     }
        //     $freelancer->assigned_projects = $assigned_projects;
        // }
        // dd($freelancer);   
        $s3url =  $this->viewVars['s3url'];
        $Subjects = TableRegistry::get("Subjects")->find('list')->where(['status' => 1])->toArray();
        $this->set(compact('freelancer', 's3url', 'Subjects'));
        $this->set('_serialize', ['freelancer']);
    }

    public function add()
    {
        $freelancer = $this->Freelancers->newEntity();
        $Subjects = TableRegistry::get("Subjects");
        $Subjects = $Subjects->find('list')->where(['status' => 1])->toArray();
        if ($this->request->is('post')) {
            $address_proof = $this->request->data['address_proof'];
            // print_r($address_proof);die;
            // pr($this->request->data);die;
            if (!empty($this->request->data['address_proof']['name'])) {
                $nameArr = [];
                $value = $this->request->data['address_proof'];
                $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 = 'workolics/profile_image/' . $name;
                $s3 = new \S3(awsAccessKey, awsSecretKey);

                $r = $s3->putObjectFile($tmp_name, bucketName, $path,  \S3::ACL_PUBLIC_READ, [], $value['type']);
                $nameArr[] = $path;
                // $this->request->data['address_proof'] = implode(',', $nameArr);
                $this->request->data['address_proof'] = $path;
            } else {
                unset($this->request->data['address_proof']);
                $this->request->data['address_proof'] = '';
            }
            $this->request->data['proficient'] = implode(',', $this->request->data['proficient']);
            $this->request->data['category_id'] = implode(',', $this->request->data['category_id']);
            $this->request->data['plain_password'] = $this->request->data['password'];
            $this->request->data['password'] = md5($this->request->data['password']);
            $freelancer = $this->Freelancers->newEntity();
            $freelancer = $this->Freelancers->patchEntity($freelancer, $this->request->data);
            if ($this->Freelancers->save($freelancer)) {
                $this->Flash->success(__('The freelancer has been saved.'));


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

        $this->set(compact('freelancer', 'Subjects'));
        $this->set('_serialize', ['freelancer']);
    }

    public function edit($id = null)
    {
        $freelancer = $this->Freelancers->get($id, [
            'contain' => []
        ]);
        $address_proof = 'address_proof/' . $freelancer['address_proof'];
        $Subjects = TableRegistry::get("Subjects");
        $Subjects = $Subjects->find('list')->where(['status' => 1])->toArray();
        if ($this->request->is(['patch', 'post', 'put'])) {
            // dd( ( $this->request->data));
            // pr($this->request->data);die;
            if (!empty($this->request->data['address_proof']['name'])) {
                $nameArr = [];
                $value = $this->request->data['address_proof'];
                $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 = 'address_proof/' . $name;
                $s3 = new \S3(awsAccessKey, awsSecretKey);

                $r = $s3->putObjectFile($tmp_name, bucketName, 'workolics/address_proof/' . $value['name'],  \S3::ACL_PUBLIC_READ, [], $value['type']);
                $nameArr[] = $path;
                $this->request->data['address_proof'] = $value['name'];
            } else {
                unset($this->request->data['address_proof']);
                // $this->request->data['address_proof'] = '';
            }
            if (empty($this->request->data['pan_card']['name'])) {
                unset($this->request->data['pan_card']);
            }
            if (empty($this->request->data['cheque']['name'])) {
                unset($this->request->data['cheque']);
            }
            $this->request->data['proficient'] = implode(',', $this->request->data['proficient']);
            @$this->request->data['category_id'] = implode(',', @$this->request->data['category_id']);
            $this->request->data['plain_password'] = @$this->request->data['password'];
            $this->request->data['password'] = md5(@$this->request->data['password']);
            $freelancer = $this->Freelancers->patchEntity($freelancer, $this->request->data);
            if ($this->Freelancers->save($freelancer)) {
                $this->Flash->success(__('The freelancer has been saved.'));
                (@$this->request->data['close']) ? $redirect = $this->redirect(['action' => 'index']) : $redirect = $this->redirect($this->here);

                return @$redirect;
            }
            $this->Flash->error(__('The freelancer could not be saved. Please, try again.'));
        }
        $this->set(compact('freelancer', 'Subjects', 'address_proof'));
        $this->set('_serialize', ['freelancer']);
    }

    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $freelancer = $this->Freelancers->get($id);
        $freelancer->delete_status = 1;
        $freelancer->delete_by = $this->Auth->user('id');
        // if ($this->Freelancers->delete($freelancer)) {
        if ($this->Freelancers->save($freelancer)) {
            $this->Flash->success(__('The freelancer has been deleted.'));
        } else {
            $this->Flash->error(__('The freelancer could not be deleted. Please, try again.'));
        }

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

    public function export()
    {

        $filename = 'Freelancers-' . date('d M,Y h:i A');

        $results = $this->Freelancers->find('all')->toArray();
        //pr($results);exit;
        $csv_file = fopen('php://output', 'w');

        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $header_row = array("ID", "NAME", "EMAIL", "MOBILE", "SKYPE", "COUNTRY", "STATE", "CITY", "PINCODE", "EXPERIENCE", "DEGREE");

        fputcsv($csv_file, $header_row, ',', '"');
        foreach ($results as $result) {

            $row = array(
                $result['id'],
                $result['name'],
                $result['email'],
                $result['mobile'],
                $result['skyp_id'],
                $result['country'],
                $result['state'],
                $result['city'],
                $result['experience'],
                $result['pin_code'],
                $result['degree']
            );

            fputcsv($csv_file, $row, ',', '"');
        }

        fclose($csv_file);

        $this->render(false);
        exit;
    }

    public function approveProfile()
    {
        if ($this->request->is('post') && $this->request->data['id'] != '') {
            // $password = "user123";

            $get_freelancer_plain_pass = $this->Freelancers->get($this->request->data['id']);
            $original_password = base64_decode($get_freelancer_plain_pass['plain_password']);
            $baseUrl = 'https://www.workolics.com/';
            $websiteEmail = 'support@workolics.com';
            $email = new Email();
            $email->transport('mail');
            try {
                //->from([$this->request->data['email'] => $this->request->data['name']])
                $res = $email->viewVars(['name' => $this->request->data['name'], 'email' => $this->request->data['email'], 'password' => $original_password, 'baseUrl' => $baseUrl, 'websiteEmail' => $websiteEmail])
                    ->template('approve', 'default')
                    ->emailFormat('both')
                    ->to([$this->request->data['email'] => $this->request->data['name']])
                    ->subject('Your account has been approved')
                    ->send();
            } catch (Exception $e) {
                echo 'Exception : ',  $e->getMessage(), "\n";
            }

            TableRegistry::get('Freelancers')->updateAll(
                ["status" => 1, "reg_stage" => 4, "email_verify" => 1, 'approve_date' => date('y-m-d h:i:s'), 'approve_alert' => 0],
                ["id" => $this->request->data['id']]
            );
            // $use  = TableRegistry::get('CategoryToFreelancer')->find('all')->where(["freelancer_id" => $this->request->data['freelancer_id'],'category_id'=>$this->request->data['category_id']])->first();
            TableRegistry::get('CategoryToFreelancer')->updateAll(
                ["status" => 2, 'approve_date' => date('Y-m-d h:i:s'), 'rating' => $this->request->data['rating']],
                ["freelancer_id" => $this->request->data['freelancer_id'], 'category_id' => $this->request->data['category_id']]
            );
            TableRegistry::get('EssayTest')->updateAll(
                ["remark" =>  $this->request->data['reason'], 'result' => 1],
                ["id" => $this->request->data['essay_id']]
            );
        }

        return $this->redirect(['action' => 'index']);
        exit;
    }
    public function rejectProfile()
    {
        if ($this->request->is('post') && $this->request->data['id'] != '') {
            // $password = "user123";
            $get_freelancer_plain_pass = $this->Freelancers->get($this->request->data['id']);
            $original_password = base64_decode($get_freelancer_plain_pass['plain_password']);
            $baseUrl = 'https://www.workolics.com/';
            $websiteEmail = 'support@workolics.com';
            $email = new Email();
            $email->transport('mail');
            try {
                //->from([$this->request->data['email'] => $this->request->data['name']])
                $res = $email->viewVars(['name' => $this->request->data['name'], 'email' => $this->request->data['email'], 'reason' => $this->request->data['reason'], 'password' => $original_password, 'baseUrl' => $baseUrl, 'websiteEmail' => $websiteEmail])
                    ->template('reject', 'default')
                    ->emailFormat('both')
                    ->to([$this->request->data['email'] => $this->request->data['name']])
                    ->subject('Your Status of Application at Workolics')
                    ->send();
            } catch (Exception $e) {
                echo 'Exception : ',  $e->getMessage(), "\n";
            }

            if (!empty($this->request->data['id'])) {
                TableRegistry::get('Freelancers')->updateAll(
                    ["status" => 0],
                    ["id" => $this->request->data['id']]
                );
                TableRegistry::get('CategoryToFreelancer')->updateAll(
                    ["status" => 3, 'approve_date' => date('Y-m-d h:i:s')],
                    ["freelancer_id" => $this->request->data['freelancer_id'], 'category_id' => $this->request->data['category_id']]
                );
                TableRegistry::get('EssayTest')->updateAll(
                    ["remark" =>  $this->request->data['reason'], 'result' => 2],
                    ["id" => $this->request->data['essay_id']]
                );
            }
        }
        return $this->redirect(['action' => 'index']);
        exit;
    }
    public function userData()
    {
        if ($this->request->is('post') && $this->request->data['id'] != '') {
            $freelancer = $this->Freelancers->get($this->request->data['id']);
        }
        print($freelancer);
        die;
    }
    public function userEmail()
    {
        if ($this->request->is(['post', 'put'])) {
            // $password = "user123";
            $get_freelancer_plain_pass = $this->Freelancers->get($this->request->data['id']);
            $original_password = base64_decode($get_freelancer_plain_pass['plain_password']);
            $baseUrl = 'https://www.workolics.com/';
            $websiteEmail = 'support@workolics.com';
            $email = new Email();
            $email->transport('mail');
            try {
                $res = $email->viewVars(['name' => $this->request->data['name'], 'from' => $this->request->data['from'], 'body' => $this->request->data['body'], 'password' => $original_password, 'baseUrl' => $baseUrl, 'websiteEmail' => $websiteEmail])
                    ->template('custom_email', 'default')
                    ->emailFormat('both')
                    ->to([$this->request->data['from'] => $this->request->data['name']])
                    ->subject($this->request->data['subject'])
                    ->send();
            } catch (Exception $e) {
                echo 'Exception : ',  $e->getMessage(), "\n";
            }
        }
        return $this->redirect(['action' => 'index']);
        exit;
    }
}
