<?php
namespace App\Libraries;

class Shiprocket
{
    private $url = 'https://apiv2.shiprocket.in/v1/external/';
    private $token;
    function __construct()
    {
        /*
        Constructor to generate Token
        */
        $this->token = $this->generateToken();
        
    }


    public function get_token()
    {
        /*
        Returns Token
        */
        return $this->token;
    }

    /*
      Generate Token
    */
    public function generateToken()
    {
        $setting = new \App\Models\SettingModel;
        $data = $setting->get_application_setting();
        $post['email'] = $data->shiprocket_username;
        $post['password'] = $data->shiprocket_password;
        $data_string = json_encode($post);
        $url = $this->url . 'auth/login';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr['token'];
        }
        return false;
    }

    /*
      TAdd a New Pickup Location
    */
    public function addpickup($post)
    {

        $data_string = json_encode($post);

        $url = $this->url . 'settings/company/addpickup';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }
    /*
    Generate Invoice
     */

    public function generateInvoice($post)
    {

       $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://apiv2.shiprocket.in/v1/external/orders/print/invoice',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS =>'{
            "ids": ["'.$post.'"]

        }',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
          ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
       return json_decode( $response);
    }

    /*
      Get Pickup address details from shiprcket
    */
    public function getPickupAddress()
    {

        $url = $this->url . 'settings/company/pickup';

        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        //print_r($headers); exit();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Check pincode is servicable
    */
    public function serviceability($post)
    {

        $data_string = json_encode($post);

        $url = $this->url . 'courier/serviceability';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Generate Order 
    */
    public function generateOrder($post)
    {

        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://apiv2.shiprocket.in/v1/external/orders/create/adhoc',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS =>'{
          "order_id": "'.$post['order_id'].'",
          "order_date": "'.$post['order_date'].'",
          "pickup_location": "'.$post['pickup_location'].'",
          "channel_id": "",
          "comment": "'.$post['comment'].'",
          "billing_customer_name": "'.$post['billing_customer_name'].'",
          "billing_last_name": "'.$post['billing_last_name'].'",
          "billing_address": "'.$post['billing_address'].'",
          "billing_address_2": "'.$post['billing_address_2'].'",
          "billing_city": "'.$post['billing_city'].'",
          "billing_pincode": "'.$post['billing_pincode'].'",
          "billing_state": "'.$post['billing_state'].'",
          "billing_country": "India",
          "billing_email": "'.$post['billing_email'].'",
          "billing_phone": "'.$post['billing_phone'].'",
          "shipping_is_billing": true,
          "shipping_customer_name": "",
          "shipping_last_name": "",
          "shipping_address": "",
          "shipping_address_2": "",
          "shipping_city": "",
          "shipping_pincode": "",
          "shipping_country": "",
          "shipping_state": "",
          "shipping_email": "",
          "shipping_phone": "",
          "order_items": [
            {
              "name": "'.$post['order_items']['name'].'",
              "sku": "'.$post['order_items']['sku'].'",
              "units": '.$post['order_items']['units'].',
              "selling_price": "'.$post['order_items']['selling_price'].'",
              "discount": "",
              "tax": "'.$post['order_items']['tax'].'",
              "hsn": '.rand().'
            }
          ],
          "payment_method": "'.$post['payment_method'].'",
          "shipping_charges": '.$post['shipping_charges'].',
          "giftwrap_charges": 0,
          "transaction_charges": 0,
          "total_discount": 0,
          "sub_total": '.$post['sub_total'].',
          "length": '.$post['length'].',
          "breadth": '.$post['breadth'].',
          "height": '.$post['height'].',
          "weight": '.$post['weight'].'
        }',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
          ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return $response;
    }
    /*
      Generate AWB No.
    */
    public function generateAwbNo($post)
    {

        $data_string = json_encode($post);

        $url = $this->url . 'courier/assign/awb';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Generate Pickup Request
    */
    public function generatePickup($post)
    {

        $data_string = json_encode($post);

        $url = $this->url . 'courier/generate/pickup';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Track Courier by AWB No
    */
    public function trackByAwbNo($awbNo)
    {

        $url = $this->url . 'courier/track/awb/' . $awbNo;
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Track Courier by Shipment Id
    */
    public function trackByShipmentId($shipmentId)
    {

        $url = $this->url . 'courier/track/shipment/' . $shipmentId;
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Track Courier by Order ID
    */
    public function trackByOrderId($orderId)
    {

        $url = $this->url . 'courier/track?order_id='.$orderId.'&channel_id=CUSTOM';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Track Courier by Order ID
    */
    public function postcode($post)
    {

        $data_string = json_encode($post);

        $url = $this->url . 'open/postcode/details';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Track Multiple Courier by Shipment Id
    */
    public function trackByMulipleShipmentId($post)
    {

        $data_string = json_encode($post);

        $url = $this->url . 'courier/track/awbs';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Track Multiple Courier by Shipment Id
    */
    public function generate_mani($post)
    {

        $data_string = json_encode($post);

        $url = $this->url . 'manifests/generate';
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->get_token() . ''
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonObj = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($this->isJson($jsonObj) == 1 && $jsonObj != '' && $jsonObj != 'null')
        {
            $dataArr = json_decode($jsonObj, true);
            return $dataArr;
        }
        return false;
    }

    /*
      Check if string is JSON
    */
    function isJson($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);

    }
    /*
      Writes logs in the server
    */
    function writeLog($data)
    {
        $fileName = date("Y-m-d") . ".txt";
        $fp = fopen(dirname($_SERVER["SCRIPT_FILENAME"]) . "/logs/" . $fileName, 'a+');
        $data = date("Y-m-d H:i:s") . " - " . $data;
        fwrite($fp, $data);
        fwrite($fp, "\n");
        fclose($fp);
    }
}

