<?php
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
App::uses('CakeEmail', 'Network/Email');
App::uses('Agency', 'Agency');
App::uses('Category', 'Category');
App::uses('Contact', 'Contact');
//use App\Plugin\Admin\Controller\AdminApiController;
//App::uses('MyModel', 'Model');
//$this->loadModel('Category');
//$use = array ('Agency');
///home/managepk/dev.propertypro.pk/app/Plugin/Admin/Controller/ApiController.php
//public $uses = array('Your_Model_Name');  // array('User');
//echo "<pre>";


// echo $_SESSION['User'];
// exit;
// if(!$this->Session->check('User'))
//        {
//            $this->redirect(array('controller' => 'Users', 'action' => 'login_form'));
//            exit();
//        }
//session_start();
class ApiController extends AdminAppController {
    
    public $helpers = array('Html', 'Form','Session','Paginator','Js'=> array('Jquery'));
    public $components = array('Session','Paginator','search-master.Prg');
    public $presetVars = true;
    var $paginate = array('page'=>1,'order'=>array('name'=>'asc'));
    
    public function index()
    {
        $type = $_REQUEST['type'];
        
        if($type == 'agency'){
         $this->loadModel('Agency');
     //   $this->load('Agency');
        $agency = new Agency();
        $this->layout = null;
//        if (!$id)
//        {
//            $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
//            $this->redirect(array('action' => 'index'));
//        }
        // $post = $this->set('Agency' , $this->Agency->findById($id));
//        $post =  $this->Agency->findById($id);
//        $post =  $agency->findById($id);
//        $post =  $agency->find('list');
        $post =  $agency->find('all');
        
        
        echo json_encode($post);
        exit;
        }else if($type == 'category_list'){
            $this->loadModel('Category');
            $post =  $this->Category->find('all');
            //$re['Category'] =array();
            $inner = array();
            foreach ($post as $value) {
               $inner[] =  $value['Category'];
            }
     
            $re['Category'] = $inner;
            echo json_encode($re);
            exit;
            echo json_encode($post);
            exit;  
        }else if($type == 'location_list'){
            $this->loadModel('Location');
            $post =  $this->Location->find('all');
            echo json_encode($post);
            exit;  
        }else if($type == 'save_contact'){
         /*   //if(isset($_REQUEST['json'])){
                try{
                    $this->loadModel('Contact');
                    //$ff = $this->Contact->find('all');
                    //echo "<pre>";
                    //print_r($ff);
                    //echo"</pre>";
                    //exit;
                    //$data = json_decode($_REQUEST['json']);
                    $data = (array)json_decode(file_get_contents('php://input'));
    //                echo "<pre>";
    //               // print_r( $this->Contact->findByid('105'));
    //                echo"</pre>";
    //                exit;
                    $ress = array();
                    foreach ($data as $value){
                        $this->Contact->create();
                        //$entity = $this->Contact->newEntity((array)$value,array('validate'=>false));
                        $data = array();
                        $data['category_id'] = '5';
                        $data['user_id'] = '1';
                        $data['project_id'] = 'null';
                        $data['email'] = 'client@webagency.pk';
                        $data['password'] = 'etc';
                        $data['mobile'] = '03004444444';
                        $data['intrest_in'] = 'Plot';
                        $data['company_name'] = 'Business Man';
                        $data['phone'] = '03004444444';
                        $data['name'] = 'Mr One';
                        $data['address'] = 'Thankyou';
                        $data['district'] = 'Lahore';
                        $data['state'] = 'Lahore';
                        $data['pincode'] = 'pincode';
                        $data['status'] = 'Active';
                        $data['reg_status'] = 'Live';
                        $save['Contact'] =  $data;
                        //print_r($save);die();
    //                    echo "<pre>";
    //                  //  print_r($save);
    //                    echo"</pre>";
    //                    exit;
                        if($this->Contact->save($save)){
                            
                            $res['code'] = '200';
                            $res['msg'] = 'Saved Successfully';
                        }else{
                            print_r($this->Contact);die();
                            $res['code'] = '400';
                            $res['msg'] = 'Please try again';
                        }
                        $ress[] = $res;
                        
                    }
                    print_r($ress);die();
                    echo json_encode($ress);
                    exit;
                }catch (Exception $e){
                         echo "<pre>";
                         print_r($e->getMessage());
                         echo"</pre>";
                         exit;
                }
                echo "<pre>";
                print_r($data);
                echo"</pre>";
                exit;
            //}
            $data = array();
            $data['category_id'] = '5';
            $data['user_id'] = '1';
            $data['project_id'] = 'null';
            $data['email'] = 'client@webagency.pk';
            $data['password'] = 'etc';
            $data['mobile'] = '03004444444';
            $data['intrest_in'] = 'Plot';
            $data['company_name'] = 'Business Man';
            $data['phone'] = '03004444444';
            $data['name'] = 'Mr One';
            $data['address'] = 'Thankyou';
            $data['district'] = 'Lahore';
            $data['state'] = 'Lahore';
            $data['pincode'] = 'pincode';
            $data['status'] = 'Active';
            $data['reg_status'] = 'Live';
 
            $data_e[] = $data;
            $data_e[] = $data;
            echo json_encode($data_e);
            exit;
            
        }*/
            $data = json_decode(file_get_contents('php://input'));
            //if(!empty($input)){
                try{
                    $this->loadModel('Contact');
                    $failed = array();
                    $success = array();
                    foreach($data as $item){
                        $this->Contact->create();
                        
                        $save['Contact'] =  (array)$item;
                        if($this->Contact->save($save)){
                            $success[] = $item->phone;
                        }else{
                            $failed[] = $item->phone;
                        }
                    }
                    if(!empty($success)){
                        echo json_encode(array(
                            'code'=>200,'msg'=>'Contact saved successfully'
                        ));
                    }else{
                        echo json_encode(array(
                            'code'=>400,'msg'=>'Please try again Contact not saved'
                        ));
                    }
                    exit;
                }catch (Exception $e){
                    echo $e->getMessage();
                    exit;
                }
            //}
            $data = array(
                'logs'=>array(
                    array(
                        'name'=>'Test Contact',
                        'phone'=>'03000000000',
                        'duration'=>500,
                        'date'=>'2022-01-01 00:00:00'
                    )
                ),
                'userid'=>1,
                'location_id'=>1,
                'category_id'=>1
            );

            $data_e[] = 'Form data required in given format';
            $data_e[] = $data;
            echo json_encode($data_e);
            exit;
        }else if($type == 'save_logs'){
            $input = json_decode(file_get_contents('php://input'));
            //if(!empty($input)){
                try{
                    $this->loadModel('ContactLog');
                    $this->loadModel('Contact');
                    $logs =  $input->logs;
                    $userid = intval($_REQUEST['user_id']);
                    $category =  $input->category_id;
                    $location =  $input->location_id;
                    $this->ContactLog->deleteAll(array('user_id'=>$userid));
                    if(is_object($logs)){

                        $failed = array();
                        $success = array();
                        foreach ($logs as $items){
                            $this->ContactLog->create();
                            $data = array(
                                'phone'=>@$items->phone,
                                'category_id'=>$category,
                                'location_id'=>$location,
                                'name'=>isset($items->name) ? $items->name : 'No Name',
                                'duration'=>$items->duration,
                                'direction'=>$items->direction,
                                'calldate'=>date('Y-m-d H:i:s',$items->date / 1000),
                                'created'=>date('Y-m-d H:i:s'),
                                'user_id'=>$userid
                            );
                            
                            $save['ContactLog'] =  $data;
                            if($this->ContactLog->save($save)){
                                $success[] = $items->phone;
                                
                                if(isset($items->name) && $items->name){
                                    $contact = $this->Contact->find('all',array('conditions'=>array('Contact.phone'=>$items->phone)));
                                    if(!$contact){
                                        $this->Contact->create();
                                        
                                        $this->Contact->save(array(
                                            'Contact'=>array(
                                                'name'=>$items->name,
                                                'mobile'=>$items->phone,
                                                'project_id'=>$items->project_id,
                                                'status'=>'Active',
                                                'category_id'=>$category,
                                                'location_id'=>$location,
                                                'user_id'=>$userid
                                            )
                                        ));
                                    }
                                }
                            }else{
                                $failed[] = $items->phone;
                            }
                        }
                        if(!empty($success)){
                            echo json_encode(array(
                                'code'=>200,'msg'=>'Logs saved successfully'
                            ));
                        }else{
                            echo json_encode(array(
                                'code'=>400,'msg'=>'Please try again Contact not saved'
                            ));
                        }
                        exit;
                    }
                }catch (Exception $e){
                    echo $e->getMessage();
                    exit;
                }
            //}
            die();
            $data = array(
                'logs'=>array(
                    array(
                        'name'=>'Test Contact',
                        'phone'=>'03000000000',
                        'duration'=>500,
                        'date'=>'2022-01-01 00:00:00'
                    )
                ),
                'userid'=>1,
                'location_id'=>1,
                'category_id'=>1
            );

            $data_e[] = 'Form data required in given format';
            $data_e[] = $data;
            echo json_encode($data_e);
            exit;
        }
        
           $this->render('index','ajax'); 
           exit;
         $this->Prg->commonProcess();
        $this->Paginator->settings = $this->paginate;
        $cond=array('ugroup_id'=>4);
        $this->Paginator->settings['conditions'] = array($this->Agency->parseCriteria($this->Prg->parsedParams()),$cond);
        $this->Paginator->settings['limit']=$this->pageLimit;
        $this->Paginator->settings['maxLimit']=$this->maxLimit;
        $this->set('Agency', $this->Paginator->paginate());
        $this->set('Category', $this->Paginator->paginate());
        if ($this->request->is('ajax'))
        {
            $this->render('index','ajax'); // View, Layout
        }
    }
    
//    public function beforeFilter(Event $event)
//{
//    $this->loadModel('Agency');
//    parent::beforeFilter($event);
//}
    
    public function agency($id = null)
    {
        $this->loadModel('Agency');
     //   $this->load('Agency');
        $agency = new Agency();
        $this->layout = null;
        if (!$id)
        {
            $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
            $this->redirect(array('action' => 'index'));
        }
        // $post = $this->set('Agency' , $this->Agency->findById($id));
//        $post =  $this->Agency->findById($id);
//        $post =  $agency->findById($id);
//        $post =  $agency->find('list');
        $post =  $agency->find('all');
        
        
        echo json_encode($post);
        exit;
        
       
    }
//    public function category_list()
//    {
//        $this->loadModel('Category');
//     //   $this->load('Agency');
//        $category = new Category();
//        $this->layout = null;
////        if (!$id)
////        {
////            $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
////            $this->redirect(array('action' => 'index'));
////        }
//        // $post = $this->set('Agency' , $this->Agency->findById($id));
////        $post =  $this->Agency->findById($id);
////        $post =  $agency->findById($id);
////        $post =  $agency->find('list');
//        $post =  $category->find('all');
//        
//        
//        echo json_encode($post);
//        exit;
//        
//       
//    }

}
