<?php

/**
 *
 * This Controller used to fetch  Bigcommerce Customer
 *
 * @category   Products
 * @package    Bigcommerce API
 * @author     Original Author <divya@imprintnext.com>
 * @copyright  2021-2022 Riaxe Systems
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    Release: @1.0
 */

namespace CustomerStoreSpace\Controllers;

use ComponentStoreSpace\Controllers\StoreComponent;

class StoreCustomersController extends StoreComponent {

    public function __construct() {
        parent::__construct();
    }

     /**
     * GET: Total customer count
     *
     *
     * @author divya@imprintnext.com
     * @date   31 jan 2022
     * @return Integer
     */
    public function getCustomers($request, $response, $args) {
        try{
            $storeResponse = [];
            $customers = [];
            // Get all requested Query params 
            $limit = $request->getQueryParam('perpage') ? $request->getQueryParam('perpage') : 40;
            $filters = [
                'searchString' => $request->getQueryParam('name'),
                'page' => $request->getQueryParam('page'),
                'from_date' => $request->getQueryParam('from_date'),
                'to_date' => $request->getQueryParam('to_date'),
                'customer_no_order' => $request->getQueryParam('customer_no_order'),
                'limit' => $limit,
                'order' => (!empty($request->getQueryParam('order')) && $request->getQueryParam('order') != "") ? $request->getQueryParam('order') : 'asc',
                'orderby' => (!empty($request->getQueryParam('orderby')) && $request->getQueryParam('orderby') != "") ? $request->getQueryParam('orderby') : 'id',
            ];

            //For fetching Single Product
            if (isset($args['id']) && $args['id'] != "" && $args['id'] > 0) {
                $customers = $this->getCustomerDetails($args['id']);
                $storeResponse = $customers;
            } else {
                $customers = $this->getAllCustomers($filters);
                if (!empty($customers)) {
                    $storeResponse = $customers;
                }
            }
        }catch (\Exception $e) {
            // Store exception in logs
            create_log(
                'store', 'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'get costomer details',
                        'controller' => 'storecustomercontroller',
                    ],
                ]
            );
        }
        return $storeResponse;
    }

    /**
     * GET: Total customer count
     *
     *
     * @author divya@imprintnext.com
     * @date   12 jan 2020
     * @return Integer
     */
    public function userCount() {
        return $this->storeCustomerCount();
    }

    /**
     * GET: all countries
     *
     * @author divya@imprintnext.com
     * @date   3 Jan 2022
     * @return Array of country name
     */
    public function getAllCountries($request, $response) {
        return $this->getShopCountries();
    }

   /**
     * GET:Get all states by country code
     *
     * @param $country_code 
     *
     * @author divya@imprintnext.com
     * @date   4 jan 2022
     * @return Array
     */
    public function getAllStates($request, $response , $args) {
        $countryCode = $args['country_code'];
        return $this->getProvibce($countryCode);
    }

     /**
     * POST: Delete a customer
     *
     * @param $user_id 
     *
     * @author sonali@imprintnext.com
     * @date   26 Feb 2022
     * @return Array
     */
    public function deleteCustomer($request, $response, $args) {
        $customerID = json_clean_decode($args['id'], true);
        return $this->deleteShopCustomer($customerID);
    }

    /**
     * POST: Create  a customer
     *
     * @author divya@imprintnext.com
     * @date   27 Feb 2022
     * @return Array
     */
    public function createCustomer($request, $response, $args) {
        $allPostPutVars = $request->getParsedBody();
        try {
            $result  = $this->newShopCustomer($allPostPutVars);
        } catch (\Exception $e) {
            create_log(
                'store',
                'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'Create a customer',
                        'controller' => 'storecustomercontroller',
                    ],
                ]
            );
        }
        $resultArray = json_clean_decode($result);
        if (!empty($resultArray) && $resultArray['status'] != 422 ) {
            $response = array('status' => 1, 'message' => "customer added");
        }else {
            $response = array('status' => 0, 'message' => "Customer Email or number already exists");
        }
        return $response;
    }

     /**
     * POST: Add shipping address of a customer
     *
     * @author sonali@imprintnext.com
     * @date   28 Feb 2022
     * @return String
     */
    public function createShippingAddress($request, $response, $args) {
        $allPostPutVars = $request->getParsedBody();
        try {
            if (!empty($allPostPutVars)) {
                $result  = $this->changeDefaultAddress($allPostPutVars);
                
            }
        } catch (\Exception $e) {
            // Store exception in logs
            create_log(
                'store', 'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'customer',
                        'controller' => 'storecustomercontroller',
                    ],
                ]
            );
        }
        if (!empty($result)) {
            $response = array('status' => 1, 'message' => "address added");
        }else {
            $response = array('status' => 0, 'message' => "address not created");
        }
        return $response;
    }

    /**
     * GET:User total count
     *
     * @author divya@imprintnext.com
     * @date   31st January 2022
     * @return int
     */
    public function getTotalStoreCustomer() {
        return $this->storeCustomerCount();
    }

    /**
     * GET:customer short info
     *
     ** @param $storeId
     * @author sonali@imprintnext.com
     * @date   31st January 2022
     * @return int
     */
    public function getQuoteCustomerDetails($customerId, $storeId, $shipId, $isAddress = false) {
        return $this->customerShortData($customerId,$shipId, $isAddress);
        
    }

     /**
     * Update Customer saved searches as customer groupsshipping address
     * @author sonali@imprintnext.com
     * @date   03 March 2022
     * @return array
     */
    public function updateShippingAddress($request, $response, $args) {
        $allPostPutVars = $request->getParsedBody();
        $id = $args['id'];
        return  $this->updateCustomerAddressInShop($allPostPutVars, $id);
        
    }

    /**
     * GET:Customer saved searches as customer groups
     *
     * @author divya@imprintnext.com
     * @date   03 March 2022
     * @return array
     */
    public function getAllStoreGroups($filters) {
        return $this->getCustomerSavedSearches($filters);
    }

    /**
     * GET:Customer list in a customer groups
     *
     * @author divya@imprintnext.com
     * @date   03 March 2022
     * @return array
     */
    public function getAllStoreGroupCustomers($groupID,$store_id = 1,$returnCount = false)
    {
        return $this->getStoreCustomerByGroupId($groupID, $returnCount); 
    }

    /**
     * GET:Customer details by customer group id
     *
     * @author divya@imprintnext.com
     * @date   03 March 2022
     * @return array
     */
    public function getStoreGroupById($customerGroupId)
    {
        $filters['savedSearchID'] = $customerGroupId;
        $result = $this->getCustomerSavedSearches($filters);
        return array(
            'name' => $result['data']['name']
        );
    }

    /**
     * Update:Customer list in a customer groups
     *
     * @author divya@imprintnext.com
     * @date   03 March 2022
     * @return array
     */
    public function updateStoreCustomerGroup($updateData){
        return $this->updateCustomerSavedSearch($updateData);
    }

    /**
     * Post:Customer in customer group
     *
     * @author divya@imprintnext.com
     * @date   02 March 2022
     * @return array
     */
    public function createStoreCustomerGroup($name,$customers,$store_id = 1){
        try{
            $jsonResponse = [
                'status' => 0,
                'message' => 'Customer group not created',
            ];
            $newCustGrpID = $this->createcustomerSavedSearch($name, $customers);
            if (!empty($newCustGrpID)) {
                $jsonResponse = [
                    'status' => 1,
                    'message' => 'Customer group created',
                    'data' => $newCustGrpID,
                ];
            }

        }catch(\Exception $e){
            create_log(
                'store', 'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'create customer group',
                        'controller' => 'storecustomercontroller',
                    ],
                ]
            );

        }
        
        return $jsonResponse;
    }

    /**
     * DELETE:Customer from customer groups
     *
     * @author divya@imprintnext.com
     * @date   02 March 2022
     * @return array
     */
    public function deleteStoreCustomerGroup($customerGroupId,$storeId = 1){
        return $this->deleteCustomerSavedSearch($customerGroupId);
    }

    /**
     * GETE:store customer groups ID by customer ID
     *
     * @author divya@imprintnext.com
     * @date   02 March 2022
     * @return array
     */
    public function getStoreGroupIdByCustomerId($customerId){
        return $this->savedSearchIDFromCustID($customerId);
    }
   
}