<?php
/**
 * Manage Order at Prestashop store end as well as at Admin end
 *
 * PHP version 5.6
 *
 * @category  Store_Order
 * @package   Order
 * @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 OrderStoreSpace\Controllers;

use ComponentStoreSpace\Controllers\StoreComponent;
/**
 * Store Order Controller
 *
 * @category Store_Order
 * @package  Order
 * @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 StoreOrdersController extends StoreComponent
{
    protected $storeAPIURL;
    /**
     * Initialize Construct
     *
     * @author radhanatham@riaxe.com
     * @date   13 March 2020
     */
    public function __construct()
    {
        parent::__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);
        $this->storeAPIURL = getPackageSlipUrl().'/api';
    }

    private function makeApiRequest($endpoint, $queryParams = [])
    {
        $ch = curl_init();
        // Build URL with query parameters if any
        $url = $this->storeAPIURL . $endpoint;
        if (!empty($queryParams)) {
            $url .= '?' . http_build_query($queryParams);
        }
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
        $result = curl_exec($ch);
       
        if (curl_errno($ch)) {
            create_log(
                'store', 'error',
                [
                    'message' => curl_error($ch),
                    'extra' => [
                        'module' => 'API Request',
                        'url' => $url
                    ],
                ]
            );
            curl_close($ch);
            return null;
        }
        
        curl_close($ch);
        return $result;
    }


    /**
     * Get list of orders or a Single orders from the WooCommerce API
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author radhanatham@riaxe.com
     * @date   13 March 2020
     * @return Order List in Json format
     */
    public function getOrders($request, $response, $args)
    {
        $orders = $lineItem = $storeResponse = [];
        $jsonResponse = [
            'status' => 1,
            'records' => 0,
            'total_records' => 0,
            'message' => message('Orders', 'not_found'),
            'data' => [],
        ];
        try {
            if (isset($args['id']) && $args['id'] > 0) {
                // Fetch Single Order Details
                // Get static Data from JSON
                // $data = file_get_contents($this->demoDataJSON);
                $data = $this->makeApiRequest('/getOrders/' . $args['id']);
                $jsonData = json_decode($data,true);
                $singleOrderDetails = $jsonData['getOrderDetails'];

                $singleOrderDetails['data']['orders'][0]['images'][0]['src'] = $singleOrderDetails['data']['orders'][0]['images'][0]['src'];
                $singleOrderDetails['data']['orders'][0]['images'][0]['thumbnail'] = $singleOrderDetails['data']['orders'][0]['images'][0]['thumbnail'];
                $orders = $singleOrderDetails['data'];
                $storeResponse = [
                    'total_records' => 1,
                    'order_details' => $orders,
                ];
                // End
            } else {
              
                $from = $request->getQueryParam('from') ? $request->getQueryParam('from') : date('Y-m-d', strtotime('2015-01-01'));
                $to = $request->getQueryParam('to') ? $request->getQueryParam('to') : date('Y-m-d');
                if($request->getQueryParam('action')){
                    $from = date('Y-m-d', strtotime($request->getQueryParam('start_date')));
                    $to = date('Y-m-d', strtotime($request->getQueryParam('end_date')));
                }
                // Get all requested Query params
                $filters = [
                    'search' => $request->getQueryParam('name'),
                    'page' => $request->getQueryParam('page'),
                    'sku' => $request->getQueryParam('sku'),
                    'print_type' => $request->getQueryParam('print_type'),
                    'is_customize' => $request->getQueryParam('is_customize'),
                    'order_by' => $request->getQueryParam('orderby'),
                    'order' => $request->getQueryParam('order'),
                    'to' => $to,
                    'from' => $from,
                    'per_page' => $request->getQueryParam('per_page'),
                    'customer_id' => $request->getQueryParam('customer_id'),
                ];

                if ($request->getQueryParam('is_customize')) {
                    // Get static Data from JSON
                    // $data = file_get_contents($this->demoDataJSON);
                    $data = $this->makeApiRequest('/getOrders/', $filters);
                    $jsonData = json_decode($data,true);
                    $orders = $jsonData['getOrderList'];
                    // End
                }else{
                    // Get static Data from JSON
                    // $data = file_get_contents($this->demoDataJSON);
                    $data = $this->makeApiRequest('/getOrders/', $filters);
                    $jsonData = json_decode($data,true);
                    $orders = $jsonData['getOrderList'];
                    // End
                }
                if (!empty($orders['data'])) {
                    $storeResponse = $orders;
                    $storeResponse = [
                        'total_records' => $orders['records'],
                        'order_details' => $orders['data'],
                    ];

                }
            }
        } catch (\Exception $e) {
            // Store exception in logs
            create_log(
                'store', 'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'Get orders',
                    ],
                ]
            );
        }
        return $storeResponse;
    }

    /**
     * Get list of orders from the Prestashop API
     *
     * @param $filters All order parameters
     *
     * @author radhanatham@riaxe.com
     * @date   13 March 2020
     * @return Order List in Json format
     */
    private function getAllOrders($filters)
    {
        return array();
    }

    /**
     * Get list of Order Logs
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Responce object
     * @param $args     Slim's Argument parameters
     *
     * @author radhanatham@riaxe.com
     * @date   13 March 2020
     * @return Order List in Json format
     */
    public function getStoreLogs($request, $response, $args)
    {
        $jsonResponse = [];
        // $data = file_get_contents($this->demoDataJSON);
        $data = $this->makeApiRequest('/getStoreLogs/' . $args['id']);
        $jsonData = json_decode($data,true);
        $singleOrderDetails = $jsonData['getStoreLogs'];
        $storeResp = $singleOrderDetails[0];
        $storeOrderLog = [];
        if (!empty($storeResp['id']) && $storeResp['id'] > 0) {
            $storeOrderLog[] = [
                'id' => $storeResp['id'],
                'order_id' => $storeResp['id'],
                'agent_type' => 'admin',
                'agent_id' => null,
                'store_id' => 1,
                'message' => 'Awaiting check payment',
                'log_type' => 'order_status',
                'status' => 'new',
                'created_at' => date(
                    'Y-m-d H:i:s', strtotime($storeResp['date_add'])
                ),
                'updated_at' => date(
                    'Y-m-d H:i:s', strtotime($storeResp['date_upd'])
                ),
            ];
            if (!empty($storeResp['invoice_date']) && $storeResp['invoice_date'] != "0000-00-00 00:00:00") {
                $storeOrderLog[] = [
                    'id' => $storeResp['id'],
                    'order_id' => $storeResp['id'],
                    'agent_type' => 'admin',
                    'agent_id' => null,
                    'store_id' => 1,
                    'message' => (!empty($storeResp['invoice_date'])
                        && $storeResp['invoice_date'] != "") ? 'Paid' : 'Not-paid',
                    'date_paid' => (
                        !empty($storeResp['invoice_date'])
                        && $storeResp['invoice_date'] != ""
                    ) ? $storeResp['invoice_date'] : null,
                    'payment_method' => (!empty($storeResp['payment'])
                        && $storeResp['payment'] != "")
                    ? $storeResp['payment'] : null,
                    'payment_method_title' => null,
                    'log_type' => 'payment_status',
                    'status' => 'new',
                    'created_at' => date(
                        'Y-m-d H:i:s', strtotime($storeResp['date_add'])
                    ),
                    'updated_at' => date(
                        'Y-m-d H:i:s', strtotime($storeResp['date_upd'])
                    ),
                ];
            }
        }

        return $storeOrderLog;
    }

    /**
     * GET: Get Order items
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author radhanatham@riaxe.com
     * @date   13 March 2020
     * @return json
     */
    public function orderItemDetails($request, $response, $args)
    {
        $getStoreDetails = get_store_details($request);
        $orderArray = [];
        $jsonResponse = [];
        // $data = file_get_contents($this->demoDataJSON);
        $data = $this->makeApiRequest('/orderItemDetails/' . $args['id']);
        $jsonData = json_decode($data,true);
        $jsonData = $jsonData['orderItemDetails'];
        //Get all order details by order id
        $parameters = array();        
        $singleOrderDetails = $jsonData['orders'][0];
        $lineItem = array();
        $j = 0;
        foreach ($singleOrderDetails['associations']['order_rows'] as $v) {
            $lineItem[$j]['item_id'] = $v['id'];
            $lineItem[$j]['product_id'] = $v['product_id'];
            $lineItem[$j]['name'] = $v['product_name'];
            $lineItem[$j]['quantity'] = $v['product_quantity'];
            $lineItem[$j]['print_status'] = '';
            $lineItem[$j]['variant_id'] = $v['product_attribute_id'] == 0 ? $v['product_id'] : $v['product_attribute_id'];
            $lineItem[$j]['product_sku'] = $v['product_reference'];
            $lineItem[$j]['ref_id'] = $v['ref_id'];
            $j++;
        }
        $orderArray['order_details']['order_id'] = $args['id'];
        $orderArray['order_details']['order_incremental_id'] = $args['id'];
        $orderArray['order_details']['store_id'] = $singleOrderDetails['id_shop'];
        $orderArray['order_details']['customer_id'] = $singleOrderDetails['id_customer'];
        $orderArray['order_details']['order_items'] = $lineItem;
        return $orderArray;
    }

    /**
     * GET : Default order statuses
     *
     * @author radhanatham@riaxe.com
     * @date   25 June 2020
     * @return Array
     */
    public function getDefaultOrderStatuses()
    {
        // $data = file_get_contents($this->demoDataJSON);
        $data = $this->makeApiRequest('/getDefaultOrderStatuses');
        $jsonData = json_decode($data,true);
        $jsonData = $jsonData['getDefaultOrderStatuses'];
        return $jsonData['data'];
    }

    /**
     * POST : Order Status changed
     *
     * @param orderId
     * @param orderData
     *
     * @author radhanatham@riaxe.com
     * @date   25 June 2020
     * @return Array
     */
    public function updateStoreOrderStatus($orderId, $orderData)
    {
        $orderStatus = true;
        if ($orderStatus) {
            $status = 'success';
        } else {
            $status = 'failed';
        }
        return $status;
    }

    /**
     * POST : Order placed
     *
     * @param queryArray
     *
     * @author radhanatham@riaxe.com
     * @date   16 May 2020
     * @return Array
     */
    public function storeOrder($queryArray)
    {
        $cartId = $orderId = 0;
        $customerId = $queryArray['customer_id'];
        $productData = $queryArray['product_data'];
        if (!empty($productData)) {
            $orderId = 0;
        }
        if ($orderId) {
            $orderData = ["id" => $orderId];
        } else {
            $orderData = ["id" => 0];
        }
        return $orderData;
    }

    /**
     * GET: Order details
     *
     * @param $order_id
     * @param $orderItemId
     * @param $is_customer
     * @param $store_id
     *
     * @author steve@imprintnext.com
     * @date   20 Jan 2023
     * @return Array
     */
    public function getStoreOrderLineItemDetails($order_id, $orderItemId, $is_customer, $store_id)
    {      
        return [];
    }

    /**
     * GET: Order details
     *
     * @param $ordersIds as array
     * @param $storeId
     *
     * @author steve@imprintnext.com
     * @date   08 NOV 2022
     * @return Array
     */
    public function getOrderShortDetails($ordersIds, $storeId)
    {   // $data = file_get_contents($this->demoDataJSON);
        try {
            $data = $this->makeApiRequest('/getOrderShortDetails', [
                'ids' => implode(',', $ordersIds),
                'store_id' => $storeId
            ]);
            $jsonData = json_decode($data,true);
            $singleOrderDetails = $jsonData['getOrderDetails'];
            return ($singleOrderDetails['data']);
        } catch (\Exception $e) {
            create_log(
                'store', 'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'Get order short details',
                    ],
                ]
            );
        }
        return [];
    }
    /**
     * GET: Order item details
     *
     * @param $orderId
     * @param $storeId
     *
     * @author tapasranjan@riaxe.com
     * @date   02 Jan 2024
     * @return Array
     */
    public function orderItemAttribute($orderId, $storeId) {
        // $data = file_get_contents($this->demoDataJSON);
        $data = $this->makeApiRequest('/orderItemAttribute/' . $orderId . '/' . $storeId);
        $jsonData = json_decode($data,true);
        $orderItemDetails = $jsonData['getOrderItemDetails'];
        return ($orderItemDetails['data']);
    }

}
