<?php

namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Utility\Text;
use Cake\Mailer\Email;
use App\View\Helper\CustomHelper;
// 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();
        $condition['delete_status'] = '0';
        if ($this->Auth->user('category') != 0) {
            $condition['category_id'] = $this->Auth->user('category');
        }
        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', 'category'])->where($condition)->order(['Projects.id' => 'DESC'])->toArray();
        } else {
            $this->paginate = [
                'contain' => ['Bids', 'category'],
                'conditions' => $condition,
                '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' => ['Bids', 'Freelancers']
        ]);
        // dd($project);

        // $order = TableRegistry::get('Orders')->findByProjectId($id)->first();
        // if(!empty($order)){
        //     $submitFiles = unserialize($order['attachment']);
        // }
        $Freelancers = TableRegistry::get('Freelancers');
        $bids = TableRegistry::get("Bids");
        // if(@$project->Freelancers[0]){
        //     $project->freelancer = $Freelancers->findById($project->orders[0]['freelancer_id'])->first();
        // }

        $project->bids =  $bids->find('all')->select(['Freelancers.name', 'Bids.proposal','Bids.proposal_date','Bids.proposal_desc','Bids.freelancer_id', 'Bids.allotment_status', 'Bids.created', 'Bids.id'])->contain(['Freelancers'])->where(['project_id' => $id])->toArray();
        $s3url =  $this->viewVars['s3url'];
        $delivery = TableRegistry::get('Delivery_slices')->find('all')->where(['project_id' => $project->id])->toArray();
        $timelines = TableRegistry::get('Timelines')->find('all')->where(['project_id' => $project->id])->toArray();

        $subjects = TableRegistry::get('Subjects')->find('list')->where(['status'=>1])->toArray();
        $feedback = TableRegistry::get('Feedbacks')->find('all')->where(['project_id' => $project->id])->toArray();
        $this->set(compact('project', 's3url', 'feedback','timelines','subjects','delivery'));
        $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')) {
            $projectStatus =  $this->viewVars['projectStatus'];
            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;
                // 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 {
                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']));
            $this->request->data['order_status'] = 0;
            // $this->request->data['order_id'] = 0;
        // dd($this->request->data);

            $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();

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

        $this->set(compact('project', 'subjects', 'projectStatus'));
        $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' => []
        ]);
        // dd($project); die;
        $editView=true;
        if ($this->request->is(['patch', 'post', 'put'])) {
            // dd();
            $this->request->data['filedirectory'] = 'project';
            // $this->request->data['deadline_date'] = date('y-m-d h:i:s', strtotime($this->request->data['deadline_date']));
            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;
                    // }
                    // 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);
            } else {
                unset($this->request->data['file_data']);
            }
            $this->request->data['deadline_date'] = date('Y-m-d H:i', strtotime($this->request->data['deadline_date']));
            $this->request->data['bid_expiry_date'] = date('Y-m-d H:i', 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.'));

                // if($this->request->data['referURL'] != $this->referer()) return  $this->redirect($this->request->data['referURL']);
                @($this->request->data['close']) ? $redirect = $this->redirect(['action' => 'index']) : $redirect = $this->redirect($this->here);
                return $redirect;
                // 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();
        $referURL =  $this->referer();
        $this->set(compact('project', 'subjects', 'referURL','editView'));
        $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);
        $project->delete_status = 1;
        if ($this->Projects->save($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 getFreelancer(){
        $condition=[];

        if ($this->request->is('post')) {
            $id = $this->request->data['id'];
            $cat = $this->request->data['catId'];
            if(!empty($this->request->data['date'])){
                $date = explode(' - ',$this->request->data['date']);
                $to = date('Y-m-d h:i:s',strtotime($date[0]));
                $from = date('Y-m-d h:i:s',strtotime($date[1]));
                $condition[]=['last_login >= ' => $to,'last_login <= ' => $from];
            
            $condition[]=['status' => 1,'reg_stage'=>4];
            $freelancerData = TableRegistry::get('Freelancers')->find('all')->select(['id','name', 'reg_stage', 'email', 'status', 'category_id'])->where($condition)->where(['category_id IN'=> [$cat,0]]);
            $response =$freelancerData;
            }
        }
        echo json_encode($response);
        die;
    }
    public function shareProjects()
    {
        $response =[];
        if ($this->request->is('post')) {

            $id = $this->request->data['id'];
            $project_name = $this->request->data['projectName'];
            $freelancer = $this->request->data['freelancer'];
            $baseUrl="https://workolics.com/";
            $websiteEmail="contact@workolics.com";
            $email = new Email();
            $email->transport('mail');
            try {
                    $res = $email->from(['testcognus@gmail.com' => '@Workolics'])
                        ->viewVars(['name' => $freelancer['name'], 'baseUrl' => $baseUrl, 'websiteEmail' => $websiteEmail, 'project_id' => $id, 'project_name' => $project_name])
                        ->template('projectNotify', 'default')
                        ->emailFormat('html')
                        ->to([$freelancer['email'] => $freelancer['name'] ])
                        ->subject('New Project Arrived on @workolics')
                        ->send();
                        $response =['id'=>$freelancer['id'],'email'=>$freelancer['email'],'status'=>1];

            } catch (Exception $e) {
                echo 'Exception : ',  $e->getMessage(), "\n";
            }
        }
        echo json_encode($response);
        die;
    }
    // public function reAssignProject()
    // {

    // }
    public function assignProject()
    {
        $this->loadModel('Freelancers');
       
        $project_id = $this->request->data['project_id'];
        $project = $this->Projects->get($project_id, [
            'contain' => [],
        ]);
        $baseUrl = 'https://www.workolics.com/';
        

        
       
        if ($this->request->is('post') && !empty($project)) {
            $stage = new CustomHelper(new \Cake\View\View());
            $stage = $stage->ProjectStage($project->status);
            // dd($stage);
            if(!empty(trim($project->freelancer_id) && ($stage > 1) )){
                if($project->freelancer_id == $this->request->data['freelancer_id']){
                    $this->Flash->error(__('Project Already Assign to Same Freelancer. Please,Assign another.'));
                    exit();
                }
                $oldFreelancer = $this->Freelancers->get($project->freelancer_id);
                $email = new Email();
                $email->transport('mail');
                try {
                    $cancel = $email->from(['testcognus@gmail.com' => 'Freelancer'])
                        ->viewVars(['name' => $oldFreelancer['name'], 'project_id' => $this->request->data['project_id'], 'project_name' => $this->request->data['project_name'],'baseUrl'=>$baseUrl])
                        ->template('projectCancel', 'default')
                        ->emailFormat('html')
                        ->to([$oldFreelancer['email'] => 'Project Cancle'])
                        ->subject('Project Cancel')
                        ->send();
                } catch (Exception $e) {
                    echo 'Exception : ',  $e->getMessage(), "\n";
                }
            }
            $this->request->data['submission_status'] = 0;
            $this->request->data['ratings'] = "0";
            $this->request->data['pay_status'] = "0";
            $this->request->data['status'] = 'Allotted';
            $this->request->data['allotted_date'] = date('Y-m-d h:i:s');

            $project = $this->Projects->patchEntity($project, $this->request->data);

            if ($this->Projects->save($project)) {
                $this->Flash->success(__('The project Assign Successfully.'));
                $this->loadModel('Timelines');
                $timelines = $this->Timelines->newEntity([
                    'project_id' =>  $project_id,
                    'event' => $this->request->data['status'],
                    'description' => $this->request->data['allotment_remark'],
                    'perform_by' =>$this->Auth->user('id'),
                    'freelancer_id' => $this->request->data['freelancer_id']
                ]);
                $this->Timelines->save($timelines);
                $this->loadModel('Bids');
                $bids =$this->Bids->find('all')->where(['id'=>$this->request->data['bids_id']])->first();
                $bids->allotment_status =1;
                $this->Bids->save($bids);
                $maildata = array();
                $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'],'baseUrl'=>$baseUrl])
                        ->template('assignProject', 'default')
                        ->emailFormat('html')
                        ->to([$freelancerData['email'] => 'Assigned'])
                        ->subject('Project Assigned')
                        ->send();
                } catch (Exception $e) {
                    echo 'Exception : ',  $e->getMessage(), "\n";
                }
                $this->set(compact('freelancerData'));
            }else{
                $this->Flash->error(__('The project could not be Assign. Please, try again.'));
            }
        }
    }
    public function export()
    {

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

        $results = $this->Projects->find('all')->where(['delete_status' => 0])->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;
    }
    public function flaggedOrder()
    {
        $request = $this->request->data();
        dd($request);
    }
    public function bidDetails()
    {
        $request = $this->request->data;
        $this->loadModel('Bids');
        $bids = $this->Bids->findById($request['bids'])->first()->toArray();
        if($bids){
            $this->set(compact('bids'));
            echo json_encode ( ['status'=>1,'msg'=>'Success','data'=>$bids]);
            die;
        
        }

        echo json_encode(['status'=>0,'msg'=>'Bid Details Not Found']);
        die;
    }

}
