<?php

class Shiprocket {

  private $url = 'https://apiv2.shiprocket.in/v1/external/';
  private $username = 'Mohdfaisal664@gmail.com';
  private $password = 'toyzoo';
  private $token;

  function __construct() {
    /*
      Constructor to generate Token
     */
    $this->token = $this->generateToken();
  }

  public function get_username() {
    /*
      Returns Username
     */
    return $this->username;
  }

  public function get_password() {
    /*
      Returns Password
     */
    return $this->password;
  }

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

  /*
    Generate Token
   */

  public function generateToken() {
    $post['email'] = $this->get_username();
    $post['password'] = $this->get_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;
  }

  /*
    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($ordermaster,$orderdetails) {
      
    $post['order_items'] = $orderdetails;
    
    $post['order_id'] = "TYZ000DEL0".$ordermaster['order_id'];
    $post['order_date'] = $ordermaster['order_received_date'];
    $post['pickup_location'] = 'Primary';
    $post['channel_id'] = '2071865';
    $post['comment'] = $ordermaster['last_shopping_comment'];
    $post['billing_customer_name'] = $ordermaster['billing_name'];
    $post['billing_last_name'] = $ordermaster['billing_name'];
    $post['billing_address'] = $ordermaster['billing_address'];
    $post['billing_address_2'] = $ordermaster['billing_landmark'];
    $post['billing_city'] = $ordermaster['billing_city'];
    $post['billing_pincode'] = $ordermaster['billing_zipcode'];
    $post['billing_state'] = $ordermaster['billing_state'];
    $post['billing_country'] = $ordermaster['billing_country'];
    $post['billing_email'] = $ordermaster['email'];
    $post['billing_phone'] = $ordermaster['billing_phone'];
    $post['shipping_is_billing'] = true;
    $post['shipping_customer_name'] = $ordermaster['shipping_name'];
    $post['shipping_last_name'] = $ordermaster['shipping_name'];
    $post['shipping_address'] = $ordermaster['shipping_address'];
    $post['shipping_address_2'] = $ordermaster['shipping_landmark'];
    $post['shipping_city'] = $ordermaster['shipping_city'];
    $post['shipping_pincode'] = $ordermaster['shipping_zipcode'];
    $post['shipping_state'] = $ordermaster['shipping_state'];
    $post['shipping_country'] = $ordermaster['shipping_country'];
    $post['shipping_email'] = $ordermaster['email'];
    $post['shipping_phone'] = $ordermaster['shipping_phone'];
    foreach($post['order_items'] as $key => $item){
        $post['order_items'][$key]['name'] = $item['product_name'];
        $post['order_items'][$key]['sku'] = $item['product_code'];
        $post['order_items'][$key]['units'] = $item['quantity'];
        $post['order_items'][$key]['selling_price'] = $item['product_price'];
        $post['order_items'][$key]['discount'] = $item['product_discounted_price'];
        $post['order_items'][$key]['tax'] = '';
        $post['order_items'][$key]['hsn'] = '';
    }
    
    $post['payment_method'] = $ordermaster['payment_method'];
    $post['shipping_charges'] = $ordermaster['shipping_amount'] ? $ordermaster['shipping_amount']:0;
    $post['giftwrap_charges'] = $ordermaster['cod_amount'] ? $ordermaster['cod_amount']:0;
    $post['transaction_charges'] = $ordermaster['vat_amount'] ? $ordermaster['vat_amount']:0;
    $post['total_discount'] = $ordermaster['total_discounted_price']?$ordermaster['total_discounted_price']:0;
    $post['sub_total'] = $ordermaster['total_amount'];
    $post['length'] = 10;
    $post['breadth'] =  15;
    $post['height'] = 8;
    $post['weight'] = 9;
    
    $data_string = json_encode($post);

    $url = $this->url . 'orders/create/adhoc';
    $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 AWB No.
   */
   
   
   
   public function cancelOrder($Oid){
       
    $post['ids'] = [$Oid,];

    $data_string = json_encode($post);

    $url = $this->url . 'orders/cancel';
    $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;
   }

  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 AWB No.
   */

  public function createWrapper($post) {

    $data_string = json_encode($post);

    $url = $this->url . 'shipments/create/forward-shipment';
    $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);
      $dataArr = $jsonObj;
      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;
    $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 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;
  }

  /*
    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);
  }

}
