<?php namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\FrontModel;
use App\Models\ConfiguracioModel;
use App\Models\PressupostosModel;
use http\Url;

use App\Libraries\Pdf;

class Home extends BaseController
{

    /*
     * Home
     */
	public function index()
	{

        if(session()->get('isLoggedIn')){
            $db =  db_connect();
            $configuracio = new ConfiguracioModel($db);
            $currentEmpresaId = session()->get('empresa_id_user');
            $data['empresa'] = $configuracio->getEmpresa($currentEmpresaId);
        }

        if(isset($_GET['s']) && $_GET['s'] == 1){
            /**
             * SESSION CLIENT INFO
             */
            $clientData = [
                'nomClient',
                'emailClient',
                'telClient',
                'cifClient',
                'dirClient',
                'objectiusClient',
                'seccioClient',
                'codiPresu',
                'seccioId',
                'clientId',
                'logoClient',
                'seccions'
            ];
            $session = session();
            $session->remove($clientData);
        }

        $db = db_connect();
        $seccions = new FrontModel($db);
        $data['seccions'] = $seccions->getAll();
        if(session()->get('isLoggedIn'))
            $data['clients'] = $seccions->getAllClients($currentEmpresaId);
        return view('home', $data);
	}

    /**
     * SECCION
     */
    public function seccio()
    {

        if(session()->get('isLoggedIn')){
            $db =  db_connect();
            $configuracio = new  ConfiguracioModel($db);
            $currentEmpresaId = session()->get('empresa_id_user');
            $data['empresa'] = $configuracio->getEmpresa($currentEmpresaId);
        }
        
        if($_POST)
        {
            $clientId = NULL;
            if($this->request->getPost('clientId')){
                $clientId = $this->request->getPost('clientId'); 
            }
            $nom = $this->request->getPost('nom');
            $email = $this->request->getPost('email');
            if($this->request->getPost('tel')){
                $tel = $this->request->getPost('tel'); 
            }else{
                $tel = NULL;
            }
            if($this->request->getPost('cif')){
                $cif = $this->request->getPost('cif');
            }else{
                $cif = NULL;
            }
            if($this->request->getPost('dir')){
                $dir = $this->request->getPost('dir');
            }else{
                $dir = NULL;
            }
            if($this->request->getPost('objectius')){
                $objectius = $this->request->getPost('objectius');
            }else{
                $objectius = NULL;
            }
            $seccioId = $this->request->getPost('web-opt');
            $codi = time().date('Y');

            if($this->request->getPost('logoExist')){
                $logo = $this->request->getPost('logoExist');
            }else{
                if($this->request->getFile('logo')){
                    $file = $this->request->getFile('logo');
                    $fileSize = 30000; //
                    $ext = ['png','jpg','PNG','JPG','jpeg','JPEG','gif','GIF','webp'];
                    $imageSize = $file->getSize();
                    $fileExt = $file->getExtension();

                    if(!file_exists('./uploads/clients/'.md5($cif).'.'.$fileExt)){
                        if (is_uploaded_file($_FILES['logo']['tmp_name'])) {
                            if($file->isValid() && !$file->hasMoved()){
                                $fileUploadPath = './uploads/clients/';
                                $fileName = md5($cif).'.'.$fileExt;
                
                                $file->move($fileUploadPath,$fileName);
                                $databaseFilepath='/uploads/clients/';
                                $fileNamePath = $databaseFilepath.$fileName;
        
                                $logo = $fileNamePath;
                            }
                        }
                    }else{
                        $logo = NULL;
                    }
                }else{
                    $logo = NULL;
                }
            }

            $seccionsArr = [];

            if($this->request->getPost('seccionsId')){
                $seccionsId = $this->request->getPost('seccionsId');
                sort($seccionsId);
                foreach($seccionsId as $seccio){
                    array_push($seccionsArr, $seccio);
                }
            }

            /**
             * SESSION CLIENT INFO
             */
            $clientData = [
                'nomClient'  => $nom,
                'emailClient' => $email,
                'telClient' => $tel,
                'cifClient' => $cif,
                'dirClient' => $dir,
                'objectiusClient' => $objectius,
                'seccioClient' => $seccioId,
                'codiPresu' => $codi,
                'seccioId' => implode(',', $seccionsId),
                'clientId' => $clientId,
                'logoClient' => $logo,
                'seccions' => $seccionsArr
            ];
            
            $session = session();
            $session->set($clientData);
            //
            $db = db_connect();
            $seccions = new  FrontModel($db);
            if(count($seccionsId) == 1){
                $data['opcions'] = $seccions->getAllOpcions($seccionsId[0]);
            }else{
                $data['opcions'] = $seccions->getAllOpcionsMultiple($seccionsArr);
            }
            $data['seccio'] = $seccions->getSeccio($seccionsId[0]);
            $data['seccioId'] = implode(',', $seccionsId);
            return view('seccio', $data);
        }else{
            return  redirect()->to(base_url());
        }
    }

    /**
     * RESUM
     */
    public function resum()
    {

        if(session()->get('isLoggedIn')){
            $db =  db_connect();
            $configuracio = new  ConfiguracioModel($db);
            $currentEmpresaId = session()->get('empresa_id_user');
            $data['empresa'] = $configuracio->getEmpresa($currentEmpresaId);
        }

        if($_POST)
        {
            $db = db_connect();
            $seccions = new  FrontModel($db);

            $data['seccioId'] = $this->request->getPost('seccioId');
            $data['seccio'] = $seccions->getSeccio($this->request->getPost('seccioId'));
            $data['multiple'] = $this->request->getPost('opcioItem');
            $data['comentarisOpcio'] = $this->request->getPost('comentarisOpcio');
            $data['pagines'] = $this->request->getPost('pagines');
            $data['boxTotal'] = $this->request->getPost('boxTotal');
            if($this->request->getPost('comentarisPagines')){
                $data['comentarisPagines'] = $this->request->getPost('comentarisPagines');
            }else{
                $data['comentarisPagines'] = '';
            }
            $data['seccionsId'] = $this->request->getPost('seccionsId');
            $opcions = $this->request->getPost('opcions');
            $opcionsUnica = $this->request->getPost('opcionsUnica');
            $unica = [];
            $opcionsArr = [];
            $allItems = [];
            //print_r($opcionsUnica);
            $data['opcionsRange'] = $this->request->getPost('opcionsRange');
            foreach($opcionsUnica as $op){
                if(!empty($this->request->getPost('opcio-'.$op))){
                    $modId = $this->request->getPost('opcio-'.$op);
                    //echo $modId.'<br>';
                    $modsUnic = $seccions->getModsResum($modId);
                    array_push($unica, $modsUnic);
                    array_push($allItems, $modId);
                    //array_push($unica, $this->request->getPost('opcio-'.$i));
                }
            }

            if($opcions){
                for($i=0;$i<=count($opcions);$i++){
                    if(!empty($opcions[$i])){
                        $modsMultiple = $seccions->getOpcio($opcions[$i]);
                        array_push($opcionsArr, $modsMultiple);
                        //array_push($unica, $this->request->getPost('opcio-'.$i));
                    }
                }
            }

            if(!empty($data['multiple'])){
                foreach($data['multiple'] as $opcio){
                    array_push($allItems, $opcio);
                }
            }
            
            $data['total'] = $this->request->getPost('total');
            $data['unics'] = $unica;
            $data['opcions'] = $opcionsArr;
            $allItems = implode(",", $allItems);
            $data['allItems'] = $allItems;
            $data['isPressupost'] = NULL;
            if($this->request->getPost('isPressupost')){
                $data['isPressupost'] = true;
            }
            if($this->request->getPost('pressupostId')){
                $pressupostId = $this->request->getPost('pressupostId');
                $db =  db_connect();
                $pressupost = new  PressupostosModel($db);
                $data['pressupost'] = $pressupost->getPressupost($pressupostId);
            }

            return view('resum', $data);
        }else{
            return  redirect()->to(base_url());
        }
    }

    public function contractar()
    {
        $session = session();
        if(!session()->get('isLoggedIn')){
            return  redirect()->to(base_url().'/auth');
        }
        if($_POST)
        {
            $db =  db_connect();
            $currentEmpresaId = session()->get('empresa_id_user');
            $clientId = session()->get('clientId');

            if($clientId == NULL){
                //CLIENT
                $nom = session()->get('nomClient');
                $email = session()->get('emailClient');
                $tel = session()->get('telClient');
                $cif = session()->get('cifClient');
                $dir = session()->get('dirClient');
                $logo = session()->get('logoClient');

                $data = [
                    'empresa_id_client' => $currentEmpresaId,
                    'nom_client' => $nom,
                    'email_client' => $email,
                    'tel_client' => $tel,
                    'cif_client' => $cif,
                    'dir_client' => $dir,
                    'logo_client' => $logo
                ];
                
                $builder = $db->table('clients');

                $builder->insert($data);
            }

            //signatura
            $imgBase = $this->request->getPost('firma');

            if($imgBase){
            list($type, $data) = explode(';', $imgBase);
            list(, $imgBase) = explode(',', $imgBase);
            $imgBase = base64_decode($imgBase);
            $imgName = time().rand(0,10).'.png';
            if(file_put_contents('./uploads/signatures/'.$imgName, $imgBase)){

                $signatura = $imgName;
            }else{
                $signatura = NULL;
            }
            }else{
                return NULL;
            }

            //PRESSUPOST
            $num = session('codiPresu');
            $data = date('d-m-Y');
            $preu = $this->request->getPost('preu');
            $objectius = session('objectiusClient');
            
            if($clientId){
                $client = $clientId;
            }else{
                $client = $db->insertID();
            }

            $seccioId = $this->request->getPost('seccioId');
            $resum = $this->request->getPost('resum');
            $items = $this->request->getPost('items');
            $comentaris = $this->request->getPost('comentaris');
            $boxTotal = $this->request->getPost('boxTotal');
            $pdfName = 'pressupost-'.$num;
            if($this->request->getPost('pagament')){
                $pagament = $this->request->getPost('pagament');
            }else{
                $pagament = NULL;
            }

            $data = [
                'empresa_id_pressupost' => $currentEmpresaId,
                'num_pressupost' => $num,
                'data_pressupost' => $data,
                'preu_pressupost' => $preu,
                'objectius_pressupost' => $objectius,
                'client_id_pressupost' => $client,
                'seccio_id_pressupost' => $seccioId,
                'resum_pressupost' => $resum,
                'items_pressupost' => $items,
                'comentaris_items_pressupost' => $comentaris,
                'estimation_pressupost' => $boxTotal,
                'signatura_pressupost' => $signatura,
                'pagament_pressupost' => $pagament,
                'pdf_pressupost' => $pdfName
            ];

            $builder = $db->table('pressupostos');
            if($builder->insert($data)){

                //PDF
                $lastPressupostId = $db->insertID();
                $db =  db_connect();
                $pressupostos = new  PressupostosModel($db);
                $data['pressupost'] = $pressupostos->getResumPressupost($lastPressupostId);
                $configuracio = new ConfiguracioModel($db);
                $data['empresa'] = $configuracio->getEmpresa($currentEmpresaId);
                $html = view('pdfPressupost', $data);
                $pdf = new Pdf();
                $pdf->createPDF($html, $pdfName, false, 'A4', 'portrait');

                $session->setFlashdata('success', 'Pressupost creat correctament');
                return redirect()->to(base_url().'/pressupostos/resumpressupost/'.$lastPressupostId);
            }else{
                $session->setFlashdata('error', 'Hi ha hagut un error');
                return redirect()->to(base_url().'/home/resum');
            }
            
        }else{
            return  redirect()->to(base_url().'/home/resum');
        }
    }

    public function getClients()
    {
        if($_POST)
        {
            $id = $this->request->getPost('id');

            $db = db_connect();
            $clients = new FrontModel($db);
            $result = $clients->getClient($id);
            return json_encode($result);
        }else{
            return false;
        }
    }

}
