<?php

/**
 * companies table's controller.
 *
 * Used to perform operations on companies table.
 *
 * @author Mario Vallejo <wappsi.desarrollomovil01@gmail.com>
 */

namespace App\Controllers;

use App\Models\SmaCompaniesModel;
use App\Validation\SmaCompaniesValidation;
use CodeIgniter\RESTful\ResourceController;
use Throwable;

class SmaCompanies extends ResourceController
{
    /**
     * Get updated rows form companies table.
     *
     * 
     * Based on last_sync value (from request), return updated rows from companies.
     *
     * Request should contain last_sync value (date) to get updated rows based on
     * that date.
     *
     * If request contains first_time = true, it returns all data in companies table.
     * 
     * Validation rules and messages are taken from SmaCompaniesValidation file.
     *
     * @filesource App/Validation/SmaCompaniesValidation
     *
     * @return  HttpResponse
     */
    public function sync()
    {
        $this->setModel(new SmaCompaniesModel($this->dbGroupFromRequest()));

        $rules = SmaCompaniesValidation::getSyncRules();
        $this->request;
        $message = SmaCompaniesValidation::getSyncMessages();
        if (!$this->validate($rules, $message)) {

            // if validation fails

            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => [],
                'date' => $this->request->getVar('last_sync'),
            ];

            return $this->respondCreated($response);
        } else {
            // validate
            $item_list = [];
            helper('jwt');
            $authHeader = $this->request->getServer('HTTP_AUTHORIZATION');
            $token = getJWTFromRequest($authHeader);
            $view_right = viewRightFromJWT($token);
            $user_id = userIdFromJWT($authHeader);

            $filter_to_all = ['status' => 1, 'group_name' => 'customer'];

            $filter_to_update = null;
            // to take user company too
            $user_or_filter = null;

            // to get user biller
            $user_data = SmaUsers::getUserData($user_id,$this->dbGroupFromRequest());
            $billerD = json_decode($user_data['biller_id']);
            $billerId = 0;
            if(is_array($billerD)){
                $billerId = $billerD[0];
            }else{
                $billerId = $user_data['biller_id'];
            }
            $user_or_filter = ['id=' =>$billerId];
            if ($view_right == 0) {
                //to get biller default customer
                $biller_def_customer = SmaBillerData::getBillerDefaultCustomer($billerId, $this->dbGroupFromRequest());
                $user_or_filter['id'] = $biller_def_customer;

                $filter_to_all['customer_seller_id_assigned'] = $user_data['seller_id'];
                $filter_to_update = ['customer_seller_id_assigned' => $user_data['seller_id']];
                // print_r($user_or_filter);
            }
            if ($this->request->getVar('first_time') == true) {

                $item_list = $this->getAllRows(['id' => 'id_cloud'], $filter_to_all, $user_or_filter);
            } else if ($this->request->getVar('first_time') == false) {
                $item_list = $this->getUpdatedRows(['id' => 'id_cloud'], $filter_to_update, $user_or_filter);
            } else {
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => 'EL campo "first_time" no es valido',
                    'data' => [],
                ];

                return $this->respondCreated($response);
            }

            $response = [
                'status' => 200,
                'error' => false,
                'message' => 'Exito',
                'server_date_time' => $this->getServerDateTime(),
                'data' => $item_list,
            ];

            return $this->respondCreated($response);
        }
    }

    /**
     * Get updated suppliers only function.
     * 
     * Based on last_sync value (from request), return updated rows from companies.
     *
     * Request should contain last_sync value (date) to get updated rows based on
     * that date.
     *
     * * Validation rules and messages are taken from SmaCompaniesValidation file.
     *
     * @filesource App/Validation/SmaCompaniesValidation
     * 
     * @return HttpResponse
     */
    public function syncSuppliers()
    {

        $this->setModel(new SmaCompaniesModel($this->dbGroupFromRequest()));

        $rules = SmaCompaniesValidation::getSyncRules();
        $this->request;
        $message = SmaCompaniesValidation::getSyncMessages();
        // echo $this->request->();
        if (!$this->validate($rules, $message)) {
            // if validation fails
            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => [],
                'date' => $this->request->getVar('last_sync'),
            ];
            return $this->respondCreated($response);
        } else {
            // validate
            $item_list = [];

            $filter_to_all = ['status' => 1, 'group_name' => 'supplier'];

            if ($this->request->getVar('first_time') == true) {

                $item_list = $this->getAllRows(['id' => 'id_cloud'], $filter_to_all);
            } else if ($this->request->getVar('first_time') == false) {

                $item_list = $this->getUpdatedRows(['id' => 'id_cloud'], $filter_to_all);
            } else {
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => 'EL campo "first_time" no es valido',
                    'data' => [],
                ];

                return $this->respondCreated($response);
            }

            $response = [
                'status' => 200,
                'error' => false,
                'message' => 'Exito',
                'server_date_time' => $this->getServerDateTime(),
                'data' => $item_list,
            ];

            return $this->respondCreated($response);
        }
    }

    /**
     * Creates new row on companies.
     * 
     * Creates a new Customer on database sma_companies, with given data in a post http.
     *
     * 
     * Validation rules and messages are taken from SmaCompaniesValidation file.
     *
     * @filesource App/Validation/SmaCompaniesValidation
     * 
     * @todo Create validations for customer creation data.
     *
     * @return  HttpResponse
     */
    public function addCustomer()
    {
        // $rules = SmaCompaniesValidation::getCreateCustomerRules();
        // $this->request;
        // $message = SmaCompaniesValidation::getCreateCustomerMessages();

        $response = [];
        try {
            // converting tada into array
            $companyInfo = $this->request->getJSON(true);
            // echo 'Company info =>';
            // print_r($companyInfo);
            $user_data = [];
            $favorites_data = [];
            $location_data = [];
            // $user_model = null;
            // print_r($companyInfo);
            if (array_key_exists('user_data', $companyInfo)) {
                // Get user info ready to insert in sma_users
                $user_data = $companyInfo['user_data'];
                unset($companyInfo['user_data']);
                $user_data['first_name'] = $companyInfo['first_name'];
                $user_data['last_name'] = $companyInfo['first_lastname'];
                $user_data['company'] = $companyInfo['company'];
                $user_data['email'] = $companyInfo['email'];
                $user_data['company'] = $companyInfo['company'];
                $user_data['phone'] = $companyInfo['phone'];
                $user_data['group_id'] = $companyInfo['group_id'];
                $user_data['active'] = 1;

                // take image data

                if (array_key_exists('favorites', $companyInfo)) {
                    $favorites_data = $companyInfo['favorites'];
                    unset($companyInfo['favorites']);
                }
            } else if (array_key_exists('favorites', $companyInfo)) {
                unset($companyInfo['favorites']);
            }

            if (isset($companyInfo["image"])) {
                $file = $companyInfo["image"];
                // print_r($file);
                unset($companyInfo['image']);
                $fileName = uniqid();

                helper('jwt');
                $authHeader = $this->request->getServer('HTTP_AUTHORIZATION');
                $token = getJWTFromRequest($authHeader);
                $company_folder = companyFolderFromJWT($token);

                // echo "..".$company_folder."assets/uploads/avatars/";

                try {
                    helper('images');

                    $result = base64_to_selected_format($file, ".." . $company_folder . "assets/uploads/avatars/" . $fileName);
                } catch (\Throwable $th) {
                    $result = false;
                }

                if ($result != false) {
                    $companyInfo['customer_profile_photo'] = $fileName . '.' . $result;
                }

                // print_r($result?1:0);
            }
            if (isset($companyInfo["geo_location"])) {
                $location_data = $companyInfo["geo_location"];
                // print_r($file);
                unset($companyInfo['geo_location']);
            }
            $this->setModel(new SmaCompaniesModel($this->dbGroupFromRequest()));

            $id_company = $this->model->insert($companyInfo, true);
            // print_r($id_company);
            if (isset($id_company) && $id_company != 0) {
                try {

                    $address = [
                        'latitude' => $location_data['lat'] ?? null,
                        'longitude' => $location_data['lon'] ?? null,
                        'company_id' => $id_company,
                        'direccion' => $companyInfo['address'] ?? '',
                        'sucursal' => $companyInfo['name'],
                        'customer_address_seller_id_assigned' => $companyInfo['customer_seller_id_assigned'],
                        'city' => $companyInfo['city'],
                        'state' => $companyInfo['state'],
                        'country' => $companyInfo['country'],
                        'phone' => $companyInfo['phone'],
                        'city_code' => $companyInfo['city_code'],
                        'customer_group_id' => $companyInfo['customer_group_id'],
                        'customer_group_name' => $companyInfo['customer_group_name'],
                        'price_group_name' => $companyInfo['price_group_name'],
                        'price_group_id' => $companyInfo['price_group_id'],
                        'email' => $companyInfo['email'],
                        "location" => $companyInfo['location'] ?? null,
                        "subzone" => $companyInfo['subzone'] ?? null,
                        'code' => $companyInfo['vat_no'] . '-01',

                    ];

                    try {
                        unset($companyInfo['location']);
                        unset($companyInfo['subzone']);
                    } catch (\Throwable $th) {
                        //throw $th;
                    }
                    // print_r($address);

                    // set company id of user
                    if (!empty($user_data)) {
                        $user_data['company_id'] = $id_company;

                        // insert user into db$user_model = new SmaUsers();
                        $user_id = SmaUsers::createUser($user_data, $this->dbGroupFromRequest());

                        if (!empty($favorites_data)) {

                            $favorites_array = [];

                            for ($i = 0; $i < count($favorites_data); ++$i) {
                                array_push($favorites_array, ["user_id" => $user_id, "product_id" => $favorites_data[$i]]);
                            }
                            SmaWishlist::addFavorites($favorites_array, $this->dbGroupFromRequest());
                        }
                    }

                    $address_id = SmaAddresses::createAddressFromArray($address, $this->dbGroupFromRequest());

                    if (isset($address_id) && $address_id != 0) {
                        $response = [
                            'status' => 200,
                            'error' => false,
                            'company_id' => $id_company,
                            'address_id' => $address_id,
                            'customer_profile_photo' => $companyInfo['customer_profile_photo'] ?? null,
                            'message' => 'Cliente creado exitosamente',
                            'server_date_time' => $this->getServerDateTime(),
                        ];
                    } else {
                        $this->model->delete($id_company);
                    }
                } catch (\Throwable $th) {
                    $response = [
                        'status' => 400,
                        'error' => true,
                        'message' => $th,
                        'server_date_time' => $this->getServerDateTime(),
                    ];
                }
            } else {
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => 'Error al crear nuevo tercero',
                    'server_date_time' => $this->getServerDateTime(),
                ];
            }
        } catch (Throwable $th) {
            $response = [
                'status' => 400,
                'error' => true,
                'message' => "Error al crear company",
                'data' => [],
            ];
        }
        return $this->respondCreated($response);
    }

    /**
     * Creates a new Customer on database sma_companies, with given data in a post http
     *
     * @return void
     */
    public function addCompany()
    {
        // $rules = SmaCompaniesValidation::getCreateCustomerRules();
        // $this->request;
        // $message = SmaCompaniesValidation::getCreateCustomerMessages();

        // echo $this->request->();
        //TODO: Create validations for this
        $response = [];

        try {

            // converting tada into array
            $data = $this->request->getJSON(true);
            // echo 'Company info =>';
            // print_r($companyInfo);
            $companyInfo = $data['company_data'];
            // $user_data = [];
            $favorites_data = $data['favorites'] ?? null;
            $user_data = $data["user_data"] ?? null;
            $address = $data["address_data"];
            // $user_model = null;
            // print_r($companyInfo);


            if (isset($data["image"])) {
                $file = $data["image"];
                // print_r($file);
                unset($data['image']);
                $fileName = uniqid();

                helper('jwt');
                $authHeader = $this->request->getServer('HTTP_AUTHORIZATION');
                $token = getJWTFromRequest($authHeader);
                $company_folder = companyFolderFromJWT($token);

                // echo "..".$company_folder."assets/uploads/avatars/";

                try {
                    helper('images');

                    $result = base64_to_selected_format($file, ".." . $company_folder . "assets/uploads/avatars/" . $fileName);
                } catch (\Throwable $th) {
                    // throw($th);
                    $result = false;
                }

                if ($result != false) {
                    $companyInfo['customer_profile_photo'] = $fileName . '.' . $result;
                }

                // print_r($result?1:0);
            }

            $this->setModel(new SmaCompaniesModel($this->dbGroupFromRequest()));
            // print_r($companyInfo);
            $id_company = $this->model->insert($companyInfo, true);
            if (isset($id_company) && $id_company != 0) {
                try {

                    $address["company_id"] = $id_company;

                    // print_r($address);

                    // set company id of user
                    if (!empty($user_data)) {
                        $user_data['company_id'] = $id_company;

                        // insert user into db$user_model = new SmaUsers();
                        $user_id = SmaUsers::createUser($user_data, $this->dbGroupFromRequest());

                        if (!empty($favorites_data)) {

                            $favorites_array = [];

                            for ($i = 0; $i < count($favorites_data); ++$i) {
                                array_push($favorites_array, ["user_id" => $user_id, "product_id" => $favorites_data[$i]]);
                            }
                            SmaWishlist::addFavorites($favorites_array, $this->dbGroupFromRequest());
                        }
                    }

                    $address_id = SmaAddresses::createAddressFromArray($address, $this->dbGroupFromRequest(),);

                    if (isset($address_id) && $address_id != 0) {
                        $response = [
                            'status' => 200,
                            'error' => false,
                            'company_id' => $id_company,
                            'address_id' => $address_id,
                            'customer_profile_photo' => $companyInfo['customer_profile_photo'] ?? null,
                            'message' => 'Cliente creado exitosamente',
                            'server_date_time' => $this->getServerDateTime(),
                        ];
                    } else {
                        $this->model->delete($id_company);
                    }
                } catch (\Throwable $th) {
                    $response = [
                        'status' => 400,
                        'error' => true,
                        'message' => $th,
                        'server_date_time' => $this->getServerDateTime(),
                    ];
                }
            } else {
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => 'Error al crear nuevo tercero',
                    'server_date_time' => $this->getServerDateTime(),
                ];
            }
        } catch (Throwable $th) {
            throw ($th);

            $response = [
                'status' => 400,
                'error' => true,
                'message' => "Error al crear company",
                'data' => [],
            ];
            // throw $th;
        }
        return $this->respondCreated($response);
    }

    /**
     * Create new companies row
     *
     * Creates a new Supplier on database sma_companies, with given data in a post http.
     * 
     * 
     * Validation rules and messages are taken from SmaCompaniesValidation file.
     *
     * @filesource App/Validation/SmaCompaniesValidation
     *
     * @return HttpResponse
     */
    public function addSupplier()
    {
        $this->setModel(new SmaCompaniesModel($this->dbGroupFromRequest()));
        $rules = SmaCompaniesValidation::getCreateProviderRules();
        $this->request;
        $message = SmaCompaniesValidation::getCreateProviderMessages();

        // echo $this->request->();
        $response = [];

        if (!$this->validate($rules, $message)) {

            // if validation fails

            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => [],
            ];
        } else {
            // converting tada into array
            $companyInfo = $this->request->getJSON(true);

            $id_company = $this->model->insert($companyInfo, true);
            // print_r($id_company);
            if (isset($id_company) && $id_company != 0) {
                try {

                    $response = [
                        'status' => 200,
                        'error' => false,
                        'company_id' => $id_company,
                        // 'customer_profile_photo' => $companyInfo['customer_profile_photo'] ?? null,
                        'message' => 'Proveedor creado exitosamente',
                        'server_date_time' => $this->getServerDateTime(),
                    ];
                } catch (\Throwable $th) {
                    $response = [
                        'status' => 400,
                        'error' => true,
                        'message' => $th,
                        'server_date_time' => $this->getServerDateTime(),
                    ];
                }
            } else {
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => 'Error al crear nuevo proveedor',
                    'server_date_time' => $this->getServerDateTime(),
                ];
            }
        }
        return $this->respondCreated($response);
    }

    /**
     * Get companies first result, given a companies id.
     * 
     * Returns selected data in sma_companies, $column field is a string for select
     * who determines wich column return.
     *
     * @param int $ids
     * @return array if empty array, no data found.
     */
    public static function getCompaniesData($id, $dbGroup)
    {
        $model = new SmaCompaniesModel($dbGroup);
        $res = $model->select($model->getColumnsString())
            ->where('id', $id)
            ->first();
        // print_r($res);
        return $res;
    }
}
