<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;

use App\Models\ClientesModel;
use App\Models\EquiposModel;
use App\Models\CotizacionesModel;
use App\Models\CotizacionesarticulosModel;
use App\Models\NdeModel;
use App\Models\NdearticulosModel;
use App\Models\VentasModel;
use App\Models\VentasarticulosModel;
use App\Models\ComprasModel;
use App\Models\ComprasarticulosModel;
use App\Models\CajaModel;

class ClientesController extends BaseController
{
    public function __construct()
    {
        helper(["url", "form", "session", "epscolor"]);
        $this->epsconfig_lib = new \App\Libraries\EpsConfig_Lib();

        $this->clientes = new ClientesModel();
        $this->equipos = new EquiposModel();
        $this->cotizaciones = new CotizacionesModel();
        $this->cotizacionesarticulos = new CotizacionesarticulosModel(); 
        $this->nde = new NdeModel();
        $this->ndearticulos = new NdearticulosModel(); 
        $this->compras = new ComprasModel();
        $this->comprasarticulos = new ComprasarticulosModel();  
        $this->ventas = new VentasModel();
        $this->ventasarticulos = new VentasarticulosModel();  
        $this->caja = new CajaModel();
    }

    public function index()
    {
        $data['dataConfig'] = $this->epsconfig_lib->getData();

        $data['tablaurl'] = 'clientes/listaclientes';
        return view ('clientes/clientes_list', $data);
    }

    public function search_clientes()
    {

        $data['dataConfig'] = $this->epsconfig_lib->getData();

        $match = $this->request->getVar('search_clientes');

        $builder = $this->clientes->like('contacto', $match)->orLike('telefono1', $match)->orLike('razonsocial', $match);
        $data['clientes'] =  $builder->get()->getResult();

        /* $db = \Config\Database::connect();
        $builder = $db->table('clientes');    
        $builder->like('contacto', $match);   
        $builder->orLike('telefono1', $match);   
        $builder->orLike('rif', $match);   
        $builder->orLike('razonsocial', $match);
        $data['clientes'] = $builder->get()->getResult();*/

        return view('clientes/clientes_search', $data);
    }

    public function clientes_show($id = null)
    {
        $data['dataConfig'] = $this->epsconfig_lib->getData();
        $data['cliente'] = $this->clientes->find($id);

        $where = ['id_cliente' => $id];
        $data['equipos'] = $this->equipos->where($where)->get()->getResult();

        $db      = \Config\Database::connect();
        $builder = $db->table('ordenes');
        $builder->select('equipos.*,clientes.*,ordenes.*');
        $builder->where('ordenes.id_cliente', $id);
        $builder->join('clientes', 'ordenes.id_cliente = clientes.id');
        $builder->join('equipos', 'ordenes.id_equipo = equipos.id');
        $builder->orderBy('ordenes.id', 'DESC');

        $query = $builder->get()->getResult();
        $data['ordenes'] = $query;

        //COTIZACIONES ORDENES
        $data['cotizaciones'] = [];
        $data['cotizacionesarticulos'] = [];
        foreach ($query as $item) {
            $where1 = ['id_orden' => $item->id];
            $query1 = $this->cotizaciones->where($where1)->get()->getResult();
            $data['cotizaciones'][$item->id]= $query1;

            foreach ($query1 as $item2) {
                $where2 = ['id_orden' => $item->id];
                $query2 = $this->cotizacionesarticulos->where($where2)->get()->getResult();
                $data['cotizacionesarticulos'][$item->id] = $query2;
            }
        }

        //NDE ORDENES
        $data['nde'] = [];
        $data['ndearticulos'] = [];
        foreach ($query as $item) {
            $where1 = ['id_orden' => $item->id];
            $query1 = $this->nde->where($where1)->get()->getResult();
            $data['nde'][$item->id]= $query1;

            foreach ($query1 as $item2) {
                $where2 = ['id_orden' => $item->id];
                $query2 = $this->ndearticulos->where($where2)->get()->getResult();
                $data['ndearticulos'][$item->id] = $query2;
            }
        }

        //COTIZACIONES CLIENTE MERCANCIAS
        $where = ['id_cliente' => $id, 'id_orden' => null];
        $data['cotizacionescliente'] = $this->cotizaciones->where($where)->get()->getResult();
        $where = ['id_cliente' => $id, 'id_orden' => null];
        $data['cotiarticuloscliente'] = $this->cotizacionesarticulos->where($where)->get()->getResult();


        //NDE CLIENTE MERCANCIAS
        $where = ['id_cliente' => $id, 'id_orden' => null];
        $data['ndecliente'] = $this->nde->where($where)->get()->getResult();
        $where = ['id_cliente' => $id, 'id_orden' => null];
        $data['ndearticuloscliente'] = $this->ndearticulos->where($where)->get()->getResult();


        //COMPRAS CLIENTE MERCANCIAS
        $where = ['id_cliente' => $id, 'id_orden' => null];
        $data['comprascliente'] = $this->compras->where($where)->get()->getResult();
        $where = ['id_cliente' => $id];
        $data['comprasarticuloscliente'] = $this->comprasarticulos->where($where)->get()->getResult();


        //VENTAS CLIENTE MERCANCIAS
        $where = ['id_cliente' => $id, 'id_orden' => null];
        $data['ventascliente'] = $this->ventas->where($where)->get()->getResult();
        $where = ['id_cliente' => $id, 'id_orden' => null];
        $data['ventasarticuloscliente'] = $this->ventasarticulos->where($where)->get()->getResult();

        //CAJA BALANCE
        $where = ['id_cliente' => $id];
        $data['caja'] = $this->caja->where($where)->get()->getResult();


        return view('clientes/clientes_show', $data);
    }

    public function listaclientes() {
        $respuesta = $this->clientes->orderBy('id', 'desc')->get()->getResultArray();
        echo json_encode($respuesta);
    }

    public function clientes_list(): string
    {
        $data['dataConfig'] = $this->epsconfig_lib->getData();

        $data['tablaurl'] = 'clientes/listaclientes';
        return view ('clientes/clientes_list', $data);
    }

    public function clientes_add(): string
    {
        $data['dataConfig'] = $this->epsconfig_lib->getData();
        return view ('clientes/clientes_add', $data);
    }

    public function add_clientes()
    {
        if ($this->request->getPost()) {
            $telefono1 = formato_uppercase($this->request->getVar('telefono1'));
            $contacto  = formato_capitalize($this->request->getVar('contacto'));

            //$array = ['telefono1' => $telefono1, 'contacto' => $contacto];
            $array = ['telefono1' => $telefono1];
            $data = $this->clientes->where($array)->first();

            if ($data) {
                $mensaje = array('mensaje' => 'Telefono1 existe en la base de Datos');
                $success = array('success' => 'add_error');
                $data = array('data' => $data);

                $response = array_merge($data, $mensaje, $success);
            } else {
                $rif  = formato_uppercase($this->request->getVar('rif'));
                $razonsocial  = ucwords($this->request->getVar('razonsocial'));
                $telefono2  = formato_uppercase($this->request->getVar('telefono2'));
                $email  = formato_lowercase($this->request->getVar('email'));
                $direccion  = trim($this->request->getVar('direccion'));
                $role = formato_capitalize(trim($this->request->getVar('role')));
                $cargo = formato_capitalize(trim($this->request->getVar('cargo')));
                
                if (session()->get('user_cargo') === 'Administrador') {
                    if (!$role=='') {
                        $role  = formato_capitalize(trim($this->request->getVar('role')));
                    }
                    if (!$cargo=='') {
                        $cargo  = formato_capitalize(trim($this->request->getVar('cargo')));
                    }
                    $activo = $this->request->getVar('check_activo');
                    if(isset($activo)) {$activo = '1'; } else {$activo = '0';}

                    $password  = trim($this->request->getVar('password'));
                    if (($password === "") && (!isset($data['password']))) {
                        $password = "";
                    } else {
                        $password = $data['password'];
                    }

                    if ( $this->request->getFile('avatar')->isValid()) {
                        $imagen = $this->request->getFile('avatar');
                        $imagen_ext = $imagen2->guessExtension();
                        $imagen_name = $id . '_' . $razonsocial . '.' . $imagen_ext;
                        $imagen->move(ROOTPATH . 'public/assets/epscolor/img/clientes', $imagen_name, true);
                    } else {$imagen_name = '';}
                } else { $role = 'Cliente'; $cargo = ''; $activo = 0; $password = ''; $imagen_name = ''; }

                $data1 = [
                    "telefono1" => $telefono1,
                    "contacto" => $contacto,
                    "rif" => $rif,
                    "razonsocial" => $razonsocial,
                    "telefono2" => $telefono2,
                    "email" => $email,
                    "direccion" => $direccion,
                    "role" => $role,
                    "cargo" => $cargo,
                    "activo" => $activo,
                    "password" => $password,
                    "avatar" => $imagen_name,
                ];
                $id = $this->clientes->insert($data1);
                $data = $this->clientes->find($id);

                $mensaje = array('mensaje' => 'Cliente almacendado en la base de datos');
                $success = array('success' => 'add_ok');
                $data = array('data' => $data);

                $response = array_merge($data, $mensaje, $success);
            }
        }
        echo json_encode($response);
    }

    public function edit_clientes()
    {
        if ($this->request->getPost()) {

            $id = trim($this->request->getVar('id_cliente'));

            $array = ['id' => $id];
            $data = $this->clientes->where($array)->first();

            if ($data) {
                $telefono1 = trim($this->request->getVar('telefono1'));
                $contacto  = formato_capitalize($this->request->getVar('contacto'));
                $rif  = formato_uppercase($this->request->getVar('rif'));
                $razonsocial  = trim($this->request->getVar('razonsocial'));
                $telefono2  = trim($this->request->getVar('telefono2'));
                $email  = formato_lowercase($this->request->getVar('email'));
                $direccion  = trim($this->request->getVar('direccion'));
                $role = formato_capitalize(trim($this->request->getVar('role')));
                $cargo = formato_capitalize(trim($this->request->getVar('cargo')));
                
                if (session()->get('user_cargo') === 'Supervisor') {
                    if (!$role=='') {
                        $role  = formato_capitalize(trim($this->request->getVar('role')));
                    }
                    if (!$cargo=='') {
                        $cargo  = formato_capitalize(trim($this->request->getVar('cargo')));
                    }
                    $activo = $this->request->getVar('check_activo');
                    if(isset($activo)) {$activo = '1'; } else {$activo = '0';}

                    $password  = trim($this->request->getVar('password'));
                    if ($password === "") {
                        $password = $data['password'];
                    }

                    if ( $this->request->getFile('avatar')->isValid()) {
                        $imagen = $this->request->getFile('avatar');
                        $imagen_ext = $imagen2->guessExtension();
                        $imagen_name = $id . '_' . $razonsocial . '.' . $imagen_ext;
                        $imagen->move(ROOTPATH . 'public/assets/epscolor/img/clientes', $imagen_name, true);
                    } else {$imagen_name = '';}
                } else { $role = 'Cliente'; $cargo = ''; $activo = 0; $password = ''; $imagen_name = ''; }

                $data1 = [
                    "telefono1" => $telefono1,
                    "contacto" => $contacto,
                    "rif" => $rif,
                    "razonsocial" => $razonsocial,
                    "telefono2" => $telefono2,
                    "email" => $email,
                    "direccion" => $direccion,
                    "role" => $role,
                    "cargo" => $cargo,
                    "activo" => $activo,
                    "password" => $password,
                    "avatar" => $imagen_name,
                ];
                $this->clientes->update($id, $data1);
                $data = $this->clientes->find($id);

                $mensaje = array('mensaje' => 'Datos actualizado en la base de datos');
                $success = array('success' => 'add_ok');
                $data = array('data' => $data);
                $response = array_merge($data, $mensaje, $success);
            } else {
                $data = [];
                $mensaje = array('mensaje' => 'ID de cliente requerido');
                $success = array('success' => 'add_error');
                $data = array('data' => $data);
                $response = array_merge($data, $mensaje, $success);

            }

        }
        echo json_encode($response);
    }

}
