<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Zend\Session\Container;
use Zend\Json\Json;
use Zend\Config\Config;
use Zend\Config\Factory;
use Dashboard\Model\Booking;
use Dashboard\Model\User;
use Dashboard\Model\Bid;

class IndexController extends RestAPIClientController {

    public function __construct() {
        $this->bookingModel =    new Booking();
        $this->bidModel =    new Bid();
        $this->userModel = new User();
    }

    /**
     * index
     * @return ViewModel
     */
    public function indexAction() {
        $data = [];
        $data1 = [];
        $dataCredit = [];
        $dataWallet = [];
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        //echo '<pre>';print_r($sessionUser->userData);die();
        $user_id = $loginData['user_id'];
        $userTypeId = $loginData['user_type_id'];
        $name = $loginData['first_name'];
        $email = $loginData['email'];
        $mobile = $loginData['mobile'];
        $address = isset($loginData['address'])? $loginData['address']:'';
        $referralKey = $loginData['referral_key'];

        if ($userTypeId != 6565) {
            $dataCredit = [];
            $dataWallet = [];
        } else {
            $dataCredit = ['id' => $user_id, 'user_type_id' => $userTypeId];
            $dataWallet = ['id' => $user_id];
        }
        $dataWallet = ['id' => $user_id];
        $dataBooking = ['date'=>date('Y-m-d'),'user_id'=>$user_id,'user_type_id'=>$userTypeId];
        $bookingCount = $this->bookingModel->getBookingCounts($dataBooking);
        $current = $bookingCount[0]['current_booking'];
        $future = $bookingCount[0]['future_booking'];
        $completed = $bookingCount[0]['completed_booking'];
        //$pending = $bookingCount[0]['pending_booking'];
        $canceled = $bookingCount[0]['cancelled_booking'];
        //$total = $current + $future + $completed + $pending + $canceled;
        $total = $current + $future + $completed + $canceled;


        //call API
        $personalDetails = [
            'first_name' => $name,
            'email' => $email,
            'mobile' => $mobile,
            'address' => $address,
            'referal_key' => $referralKey,
            'company_name' => 'null',
            'user_type_id'=>$userTypeId
        ];
        //call API

        $data = ['pickup_date' => date('Y-m-d'),'user_id'=>$user_id];        
        $data1 = ['unassigned_booking' => 1, 'user_id'=>$user_id];
        $bidData = ['user_id'=>$user_id];
        $creditBalance = $this->bookingModel->getCreditBalance($dataCredit);
        $recentBookings = $this->bookingModel->getRecentBookings($data);
        $unassignedBookings = $this->bookingModel->getRecentBookings($data1);
        $walletHistory = $this->bookingModel->getWalletPoint($dataWallet);
        $walletAmount = $this->bookingModel->getWalletAmt($user_id);
        $bidListing = $this->bidModel->bidlisting($bidData);
        //echo '<pre>';print_r($bidListing);die();
        if($bidListing['responsedata']['status']=="success"){
            $bidListing = $bidListing['responsedata']['data'];
        }else{
            $bidListing = "";
        }
        //$dataUser['user_type_id'] = '3,4';
        $dataUser['user_type_id'] = '1,2,3,5,6,7,8';
        $dataUser['parent_id'] = $user_id;
        $dataUser['company_id'] = $this->config()->getConfig()->company->companyId;
        $userListing = $this->userModel->getUserList($dataUser);
        $userListing = $userListing['data']['responsedata'];
        /*$filter_array = ['signup_status' => 10,'is_active' => 4];
        $userListing = array_filter($userListing, function ($val_array) use ($filter_array) {
            $intersection = array_intersect_assoc($val_array, $filter_array);
            return (count($intersection)) === count($filter_array);
        });
        $userListing = array_values($userListing);*/
        $viewModel = new ViewModel([
            'current' => $current,
            'future' => $future,
            'completed' => $completed,
            //'pending' => $pending,
            'canceled' => $canceled,
            'total' => $total,
            'personalDetails' => $personalDetails,
            'creditBalance' => $creditBalance['responsedata'],
            'recentBookings' => $recentBookings,
            'unassignedBookings' => $unassignedBookings,
            'walletHistory' => $walletHistory['responsedata'],
            'wallet_amount' => $walletAmount,
            'bidListing' => $bidListing,
            'userListing' => $userListing,
        ]);
        return $viewModel;
    }

    public function setconfigurationAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $comp_id = $loginData['company_id'];
        $compData = $this->getCompanySetupDetails($comp_id);

        $filename = getcwd() . '/config/autoload/customconfig.php';
        $configFile = Factory::fromFile($filename);
        $configFile['site_name'] = $compData['site_name'];
        $configFile['site_title'] = $compData['site_title'];
        $configFile['global_email'] = $compData['global_email'];
        $configFile['admin_footer'] = $compData['admin_footer'];
        $configFile['admin_footer_url'] = $compData['admin_footer_url'];
        $configFile['frontend_footer'] = $compData['frontend_footer'];
        $configFile['frontend_footer_url'] = $compData['frontend_footer_url'];
        $configFile['admin_header_logo'] = $compData['admin_header_logo'];
        $configFile['frontend_header_logo'] = $compData['frontend_header_logo'];
        $configFile['admin_favicon'] = $compData['admin_favicon'];
        $configFile['frontend_favicon'] = $compData['frontend_favicon'];


        if (!Factory::toFile($filename, $configFile)) {
            $result = ['result' => false, 'message' => 'Can\'t put content to ' . $filename . 'due to file permission issue.'];
        } else {
            $result = ['result' => true, 'message' => 'Cofiguration content has been set successfully.'];
        }

        if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
            $viewModel = new JsonModel();
        }

        $viewModel->setVariables(['data' => $result]);

        return $viewModel;
    }


    public function downloadFileDataAction(){
         $request = $this->getRequest();

            $userId = $this->params()->fromQuery('userid');
            $doclevelname = $this->params()->fromQuery('filename');

            $b2bUrlbasePath = $this->config()->getConfig()->base_url->file_path;
            $b2bUrlFilePath = $this->config()->getConfig()->base_url->b2burl;

            $userUploadedDoc = $this->userModel->getUserDocument($userId,$doclevelname);

            if($userUploadedDoc['responsedata']['status']=='success'){
               $existfilename   = $userUploadedDoc['responsedata']['data'][0]['doc_file_upload'];
               if($existfilename!=''){

                     $downloadfilebasename = $b2bUrlbasePath."".$userId."/".$existfilename;
                     $downloadfilename = $b2bUrlFilePath."/".$userId."/".$existfilename;
                     $filename = basename($existfilename);

                    if (file_exists($downloadfilebasename)){
                            header('Content-Type: application/force-download');
                            header("Content-Transfer-Encoding: Binary");
                            header('Content-Disposition: inline; filename='.$existfilename);
                            header('Expires: 0');
                            header('Cache-Control: must-revalidate');
                            header('Pragma: public');
                            header('Content-Length: ' . filesize($downloadfilebasename));
                            ob_clean();
                            flush();
                            readfile($downloadfilename);
                            die();
                        } else {
                            http_response_code(404);
                            die();
                        }
               }else{
                   echo "Not file exist";die;
               }


        }

        $viewModel = new JsonModel();
        $viewModel->setVariables([]);

        return $viewModel;
    }
}
