<?php

/**
 * This Controller used to save, fetch or delete Standalone Customers
 *
 * PHP version 5.6
 *
 * @category  Customers_API
 * @package   Customers
 * @author    Radhanatha <radhanatham@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */

namespace CustomerStoreSpace\Controllers;

use ComponentStoreSpace\Controllers\StoreComponent;

/**
 * Store Customers Controller Class
 *
 * @category Customers_API
 * @package  Customers
 * @author   Radhanatha <radhanatham@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */
class StoreCustomersController extends StoreComponent
{
    public function __construct()
    {
        $this->demoDataJSON = str_replace(BASE_DIR . "/api/v1", "", RELATIVE_PATH) . "mockupData/JSON/mockData.json";
        $this->storeURL = str_replace("/" . BASE_DIR . "/api/v1/", "", BASE_URL);
    }
    /**
     * Get list of customer or a Single customer from the Magento API
     *
     * @param $request  Slim default params
     * @param $response Slim default params
     * @param $args     Slim default params
     *
     * @author radhanatham@riaxe.com
     * @date   13 March 2020
     * @return Array of list/one customer(s)
     **/
    public function getCustomers($request, $response, $args)
    {
        $storeResponse = [];
        // $data = file_get_contents($this->demoDataJSON);
        // $customerJson = json_decode($data, true);
        try {
            if (isset($args['id']) && $args['id'] > 0) {
                // Fetching Single Customer details
                // $storeResponse = $customerJson['getStoreCustomerDetailsById'];

                $customer_id = $args['id'];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, "https://twentyfour.mibmsdev.co.za/shop/api/getStoreCustomerDetails/{$customer_id}");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $result = curl_exec($ch);
                if (curl_errno($ch)) {
                    echo 'Error:' . curl_error($ch);
                }
                curl_close($ch);
                $resultArray = json_decode($result, true);
                $storeResponse = $resultArray['getStoreCustomerDetailsById'];


            } else {
                // Fetching all customers by filters
                $customerNoOrder = (!empty($request->getQueryParam('customer_no_order'))
                    && $request->getQueryParam('customer_no_order') != "")
                    ? $request->getQueryParam('customer_no_order') : '';

                $perPage = (!empty($request->getQueryParam('per_page')))
                    ? $request->getQueryParam('customer_no_order') : 10;

                $page = (!empty($request->getQueryParam('page')))
                    ? $request->getQueryParam('page') : 1;

                // if ($customerNoOrder == 'true') {
                //     $customerJson = $customerJson['getStoreCustomerDetailsTrue'];
                //     // $customerJson = '{"total_records":1,"data":[{"id":"1","first_name":"Anonymous","last_name":"Anonymous","email":"anonymous@psgdpr.com","date_created":"11\/Dec\/2020 06:14:13","last_order_id":null,"total_orders":0}]}';
                // } elseif ($customerNoOrder == 'false') {
                //     $customerJson = $customerJson['getStoreCustomerDetailsFalse'];
                //     // $customerJson = '{"total_records":1,"data":[{"id":"3","first_name":"Steve","last_name":"dsdsadsa","email":"steve@imprintnext.com","date_created":"16\/Dec\/2021 15:40:47","last_order_id":20,"total_orders":14}]}';
                // } else {
                //     $customerJson = $customerJson['getAllCustomerDetails'];
                // }

                if ($customerNoOrder) {
                    
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, "https://twentyfour.mibmsdev.co.za/shop/api/getStoreCustomerDetails?customer_no_order={$customerNoOrder}&per_page={$perPage}&page={$page}");
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    $result = curl_exec($ch);
                    if (curl_errno($ch)) {
                        echo 'Error:' . curl_error($ch);
                    }
                    curl_close($ch);
                    $resultArray = json_decode($result, true);

                    if ($customerNoOrder == 'true') {
                        $customerJson = $resultArray['getStoreCustomerDetailsTrue'];
                    }
                    if ($customerNoOrder == 'false') {
                        $customerJson = $resultArray['getStoreCustomerDetailsFalse'];
                    }
                    
                }else{

                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, "https://twentyfour.mibmsdev.co.za/shop/api/getStoreCustomerDetails?per_page={$perPage}&page={$page}");
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    $result = curl_exec($ch);
                    if (curl_errno($ch)) {
                        echo 'Error:' . curl_error($ch);
                    }
                    curl_close($ch);
                    $resultArray = json_decode($result, true);
                    $customerJson = $resultArray['getAllCustomerDetails'];
                }
                $storeResponse = [
                    'total_user' => $customerJson['total_records'],
                    'customer_list' => $customerJson['data'],
                ];
            }
        } catch (\Exception $e) {
            // Blank the array
            $storeResponse = [];
            // Store exception in logs
            create_log(
                'store',
                'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'Customer',
                    ],
                ]
            );
        }
        return $storeResponse;
    }

    /**
     * Get list of customer or a Single customer from the PrestaShop API
     *
     * @param $filters Customer filter
     *
     * @author radhanatham@riaxe.com
     * @date   13 March 2020
     * @return Array of list/one customer(s)
     **/
    private function getStoreCustomerDetails($filters)
    {
        $storeResponse = [];
        return $storeResponse;
    }
    /**
     * GET: Get all countries
     *
     *
     * @author radhanatham@riaxe.com
     * @date  10 Aug 2020
     * @return Array
     */
    public function getAllCountries($request, $response)
    {
        $result = '[{"countries_code":"IN","countries_name":"India"},{"countries_code":"GB","countries_name":"United Kingdom"}]';
        $result = json_decode($result, true);
        return $result;
    }

    /**
     * GET: Get all countries
     *
     *
     * @author radhanatham@riaxe.com
     * @date  10 Aug 2020
     * @return Array
     */
    public function getAllStates($request, $response, $args)
    {
        $result = '[{"state_code":"OD","state_name":"Odisha"},{"state_code":"BH","state_name":"Bihar"},{"state_code":"AS","state_name":"Asam"},{"state_code":"CH","state_name":"Chhatisgarh"}]';
        $result = json_decode($result, true);
        return $result;
    }

    /**
     * GET: Total customer count
     *
     *
     * @author radhanatham@riaxe.com
     * @date   10 April 2020
     * @return Integer
     */
    public function userCount($request, $response, $args)
    {
        $getTotalcustomersCount = 3;
        return $getTotalcustomersCount;
    }

    /**
     * POST: Create single multiple shipping address of a customer
     *
     * @param $user_id
     * @param $first_name
     * @param $last_name
     * @param $company
     * @param $address_1
     * @param $address_2
     * @param $city
     * @param $post_code
     * @param $country
     * @param $state
     *
     * @author radhanatham@riaxe.com
     * @date   31 march 2020
     * @return String
     */
    public function createShippingAddress($request, $response, $args)
    {
        $address_id = 1;
        if ($address_id) {
            $status = 1;
            $message = 'Created Successfully';
        } else {
            $status = 0;
            $message = 'Created Failed';
        }
        $jsonResponse = [
            'status' => $status,
            'message' => $message,
        ];
        return $jsonResponse;
    }

    /**
     * POST: Delete single multiple shipping address of a customer
     *
     * @param $id
     * @param $first_name
     * @param $last_name
     * @param $company
     * @param $address_1
     * @param $address_2
     * @param $city
     * @param $post_code
     * @param $country
     * @param $state
     *
     * @author radhanatham@riaxe.com
     * @date   31 march 2020
     * @return String
     */
    public function updateShippingAddress($request, $response, $args)
    {
        $id = $args['id'];
        if ($id) {
            $status = 1;
            $message = 'Updated Successfully';
        } else {
            $status = 0;
            $message = 'Updated Failed';
        }

        return [
            'status' => $status,
            'message' => $message,
        ];
    }

    /**
     * POST: Create  a customer
     *
     * @param $user_email
     * @param $user_password
     * @param $first_name
     * @param $last_name
     * @param $company_name
     * @param $company_url
     * @param $billing_phone
     * @param $billing_address_1
     * @param $billing_address_2
     * @param $billing_city
     * @param $billing_state_code
     * @param $billing_postcode
     * @param $billing_country_code
     * @param $shipping_address_1
     * @param $shipping_address_2
     * @param $shipping_city
     * @param $shipping_state_code
     * @param $shipping_postcode
     * @param $shipping_country_code
     *
     * @author radhanatham@riaxe.com
     * @date  10 Aug 2020
     * @return Array
     */
    public function createCustomer($request, $response, $args)
    {
        $allPostPutVars = $request->getParsedBody();
        if (!empty($allPostPutVars)) {
            $message = "Customer created successfully";
            $status = 1;
        } else {
            $status = 0;
            $message = "Invalid customer details";
        }
        return array('status' => $status, 'message' => $message);
    }
    /**
     * POST: Update a customer
     *
     * @param $user_id
     * @param $user_email
     * @param $user_password
     * @param $first_name
     * @param $last_name
     * @param $company_name
     * @param $company_url
     * @param $billing_phone
     * @param $billing_address_1
     * @param $billing_address_2
     * @param $billing_city
     * @param $billing_state_code
     * @param $billing_postcode
     * @param $billing_country_code
     * @param $shipping_address_1
     * @param $shipping_address_2
     * @param $shipping_city
     * @param $shipping_state_code
     * @param $shipping_postcode
     * @param $shipping_country_code
     *
     * @author radhanatham@riaxe.com
     * @date  10 Aug 2020
     * @return Array
     */
    public function updateCustomer($request, $response, $args)
    {
        $result = true;
        return $result;
    }

    /**
     * POST: Delete a customer
     *
     * @param $request  Slim default params
     * @param $response Slim default params
     * @param $args     Slim default params
     *
     * @author radhanatham@riaxe.com
     * @date  10 Aug 2020
     * @return Array
     */
    public function deleteCustomer($request, $response, $args)
    {
        $status = 0;
        $userIdArr = json_clean_decode($args['id'], true);
        if (!empty($userIdArr)) {
            $status = true;
        }
        if ($status) {
            $jsonResponse = [
                'status' => 1,
                'message' => 'Deleted Successfully',
            ];
        } else {
            $jsonResponse = [
                'status' => 0,
                'message' => 'Deleted Failed',
            ];
        }
        return $jsonResponse;
    }


    /**
     * GET:User total count
     *
     * * @param $storeId
     *
     * @author steve@imprintnext.com
     * @date   10 jan 2022
     * @return int
     */
    public function getTotalStoreCustomer($storeId)
    {
        $data = file_get_contents($this->demoDataJSON);
        $productJson = json_decode($data, true);
        $total_user = $productJson['getTotalStoreCustomer']['total_user'];
        return $total_user;
    }

    /**
     * GET: Get all store groups
     *
     * @author Abhilash Das <abhilashd@riaxe.com>
     * @date   24 May 2021
     * @return Array
     */
    public function getAllStoreGroups($filters)
    {
        $data = file_get_contents($this->demoDataJSON);
        $customerJson = json_decode($data, true);
        $storeResponse['data'] = $customerJson['getAllStoreGroups']['data'];
        $storeResponse['total_records'] = sizeof($storeResponse['data']);
        return $storeResponse;
    }

    //get a single store group by id
    public function getStoreGroupById($groupId)
    {
        $data = file_get_contents($this->demoDataJSON);
        $customerJson = json_decode($data, true);
        $data = $customerJson['getStoreGroupById']['data'];
        if (!empty($data)) {
            $jsonData['name'] = $data[0]['name'];
        }
        return $jsonData;
    }

    //Store group create
    public function createStoreCustomerGroup($name, $customers, $store_id)
    {
        $jsonResponse = [
            'status' => 0,
            'message' => 'Customer group not created',
            'data' => null,
        ];
        $storeFormData = [];
        $storeFormData['name'] = $name;
        $storeFormData['reduction'] = 0.00;
        $storeFormData['price_display_method'] = 1;
        $storeFormData['show_prices'] = 1;
        $data = 1;
        if (!empty($data)) {
            $jsonResponse = [
                'status' => 1,
                'message' => 'Customer group created',
                'data' => $data,
            ];
        }
        return $jsonResponse;
    }

    public function deleteStoreCustomerGroup($groupId, $store_id)
    {
        if (isset($groupId)) {
            $data = 1;
            return $data;
        }
    }

    public function getStoreGroupIdByCustomerId($customerId)
    {
        if (isset($customerId) && $customerId != '') {
            return 1;
        }
    }
    /**
     * GET: Get all store groups custoremer
     *
     * @author Abhilash Das <abhilashd@riaxe.com>
     * @date   24 May 2021
     * @return Array
     */
    public function getAllStoreGroupCustomers($groupId, $store_id)
    {
        $jsonData = [];
        $data = file_get_contents($this->demoDataJSON);
        $customerJson = json_decode($data, true);
        $data = sizeof($customerJson['getAllStoreGroupCustomers']['data']);
        return $data;
    }

    public function getStoreCustomerDetailsById($customerId, $store_id)
    {
        $jsonData = [];
        $customerId = to_int($customerId);
        $data = file_get_contents($this->demoDataJSON);
        $customerJson = json_decode($data, true);
        $storeResponse = $customerJson['getStoreCustomerDetailsById'];
        if (!empty($data)) {
            $jsonData['name'] = $storeResponse['firstname'] . " " . $storeResponse['lastname'];
            $jsonData['email'] = $storeResponse['email'];
        }
        return $jsonData;
    }

    /**
     * GET:Customer details
     *
     * @param $customerId
     * @param $storeId
     * @param $shipId
     * @param $isAddress
     * 
     * @author steve@imprintnext.com
     * @date   20 Jan 2023
     * @return Array
     */
    public function getQuoteCustomerDetails($customerId, $storeId, $shipId, $isAddress = false)
    {
        $customerDetails = [];
        $data = file_get_contents($this->demoDataJSON);
        $customerJson = json_decode($data, true);
        $storeResponse = $customerJson['getStoreCustomerDetailsById'];
        return $storeResponse;
    }

    /**
     * GET:User ids
     *
     * * @param $storeId
     *
     * @author radhanatham@riaxe.com
     * @date   07 Jan 2021
     * @return int
     */
    public function getStoreCustomerId($request, $response, $args)
    {
        $customerIds = [["id" => 1], ["id" => 2]];
        return $customerIds;
    }
}
