<?php namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\CarsModel;
use App\Models\TransactionModel;
use App\Models\MessageModel;
use App\Models\UserModel;
class DashboardController extends BaseController
{
    protected $messageModel;
    protected $transactionModel;
    protected $carsModel;
    protected $userModel;
    public function __construct()
    {
        $this->messageModel = new MessageModel();
        $this->transactionModel = new TransactionModel();
        $this->carsModel = new CarsModel();
        $this->userModel = new UserModel();
    }

	public function index()
	{
        $session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
        $data = ['data' => ''];

		// Cars section needs the following data:
        // Cars published all time 106
        // Cars published now 23
        // Cars in transaction 7
        // Cars to receive payment from Buyers 7
        // Cars to receive from Sellers 5
        // Cars to be paid to Sellers 7
        // Total sold cars 55
        $data['cars_published_all_time'] = $this->carsModel->get_cars_count_admin($usr,0);
        $data['cars_published_now'] = $this->carsModel->get_cars_count_admin($usr, 1);
        $data['cars_in_transaction'] = $this->carsModel->get_cars_count_admin($usr, 2);
        //$data['cars_to_receive_payment_from_buyers'] = $this->carsModel->get_cars_count_admin($usr,3);
        //$data['cars_to_receive_from_sellers'] = $this->carsModel->get_cars_count_admin($usr, 4);
        //$data['total_to_be_paid_to_sellers'] = $this->carsModel->get_cars_count_admin($usr, 5);
        $data['total_sold_cars'] = $this->carsModel->get_cars_count_admin($usr, 6);
        
        // Transactions
        $data['active_transactions'] = $this->transactionModel->get_active_transactions_count_admin();
        $data['concluded_transactions'] = $this->transactionModel->get_concluded_transactions_count_admin();


        // Messages
        $data['messages_from_sellers'] = $this->messageModel->get_messages_count_from_sellers($usr);
        $data['messages_from_buyers'] = $this->messageModel->get_messages_count_from_buyers($usr);


        // Users
        // Active users 100
        // Active Sellers 40
        // Active Buyers 15
        // Active Clients 45
        // Approval pending users 3
        // Blocked users 2
        $data['active_users'] = $this->userModel->get_active_users_count();
        $data['active_sellers'] = $this->userModel->get_active_sellers_count();
        $data['active_buyers'] = $this->userModel->get_active_buyers_count();
        $data['active_clients'] = $this->userModel->get_active_clients_count();
        $data['approval_pending_users'] = $this->userModel->get_approval_pending_users_count();
        $data['blocked_users'] = $this->userModel->get_blocked_users_count();


		return view('dashboard/index', $data);	   
        
	}

    public function testMail(){
        			//SEND mail

        $libpath=realpath(dirname(__DIR__) . '/..');
        include_once $libpath.'/send_smtp.php';
        $msg='Testing the emailing feature of admin.zadio.bg';
        sendMyMsg('zaharia_catalin0337@yahoo.com','cars@zadio.bg','Email test from admin.zadio.bg',$msg);

        return "success";
    }
	public function search()
	{
		$data = ['data' => ''];
		$po = new PoModel();
		$co = new PoProductsModel();
		$ar = new ProductsModel();
		$pa = new PalletsModel();
		$zo = new ZonesModel();
		$in = new InventoryModel();
		$tr = new TransfersModel();
		$or = new OrderModel();
		if (isset($_POST['q'])){
	     $q = $_POST['q'];
	     $r = $pa->find($q);
	     if (isset($r)){
          $data['found'] = 'pallet';
		  $data['content'] = $r;
	     }
	     else {
          $p = $ar->select('id')->where('barcode',$q)->findAll();
          if (count($p) > 0){
	       $data['found'] = 'produs(e)';
 		   $data['content'] = $p;
 	      }
 	      else {
           $z = $zo->where('barcode',$q)->findAll();
           if (count($z) > 0){
	        $data['found'] = 'zone';
 		    $data['content'] = $z;
 	       }
 	       else {
	        $data['found'] = '';
  		    $data['content'] = [];
 	       }
 	      }
	     }
	    }
        $data['po_nr'] = $po->select('id')->countAllResults();
        $data['po_ct'] = $po->where('pallets_in', 0)->countAllResults();
        $data['po_nw'] = $po->where('po_status', 'Noua')->countAllResults();
        $data['pa_nr'] = $co->select('pallet_id')->distinct('pallet_id')->countAllResults();
        $data['ba_nr'] = $co->select('product_code')->distinct('product_code')->countAllResults();
        $data['ia_nr'] = $ar->select('id')->distinct('id')->countAllResults();
        $data['ip_nr'] = $pa->select('id')->distinct('id')->countAllResults();
        $data['iz_nr'] = $pa->select('zone_id')->distinct('zone_id')->countAllResults();
        $data['tp_nr'] = $tr->select('pallet_id')->distinct('pallet_id')->countAllResults();
        $data['ta_nr'] = $tr->select('zone_id')->distinct('zone_id')->countAllResults();
        $data['or_nr'] = $or->select('id')->where("order_status='Noua' AND order_date>now() - interval 30 day")->countAllResults();
        $data['oi_nr'] = $or->select('id')->where("order_date >now() - interval 30 day AND shiping_date	 is not null")->distinct('id')->countAllResults();
		$us = session()->get('id');
        return view('dashboard/result', $data);	   
	}
    public function search1()
    {
        helper(['form', 'url']);
        $data = [];
        $po = new PoModel();
        $query = $po->like('customer', $this->request->getVar('q'))
         ->select('customer as id, customer as text')
         ->limit(10)->get();
        $data = $query->getResult();
        $data['data'] = $po->select('customer as id', 'customer as text')->findAll();
		echo json_encode($data);
    }
    public function list()
    {
        if ($this->request->getMethod() == 'post') {
            $users = new UserModel();
            $users = $users->havingLike('firstname', $this->request->getPost('search'))->get()->getResult();
            foreach ($users as $user) {
                $response[] = array("value" => $user->id, "label" => $user->firstname);
            }
            echo json_encode($response);
        }
    } 
    public function search2()
    {
        helper(['form', 'url']);
        $data = [];
        $db      = \Config\Database::connect();
        $builder = $db->table('users');   
        $query = $builder->like('realname', $this->request->getVar('q'))
                    ->select('id, realname as text')
                    ->limit(10)->get();
        $data = $query->getResult();
        
		echo json_encode($data);
    }
}
