<?php

// Code within app\Helpers\Helper.php

namespace App\Helpers;

class Tookan {

    //private const $url = "https://api.tookanapp.com/v2/";
    const URL = "https://api.tookanapp.com/v2/";

    public static function create($invoice) {
        //d($invoice,1);
        $pickupTime = explode("-", $invoice->PickupTime);
        $deliveryTime = explode("-", $invoice->DeliveryTime);

        $description = "";

        if (count($invoice->services) > 0) {

            $i = 1;
            foreach ($invoice->services as $value) {
                $description .= '' . ($i) . ' # Service : ' . $value->Title . '';
                $description .= '# Quantity : ' . $value->Quantity . '';
                $description .= '# Price : ' . $value->Price . '';
                $description .= '# Total : ' . $value->Total . '';
                $i++;
            }
        }

        $address = $invoice->BuildingName . ', ' . $invoice->StreetName . ', ' . $invoice->PostalCode . ', ' . $invoice->Town;

        $tookanArray = array(
            'api_key' => env("TOOKAN_API_KEY"),
            'order_id' => $invoice->InvoiceNumber,
            'team_id' => env("TOOKAN_TEAM_ID"),
            'auto_assignment' => "1",
            'job_description' => $invoice->members->OrderNotes . " - " . $description,
            'job_pickup_phone' => $invoice->members->Phone,
            'job_pickup_name' => $invoice->members->FirstName . ' ' . $invoice->members->LastName,
            'job_pickup_email' => $invoice->members->EmailAddress,
            'job_pickup_address' => $address,
            'job_pickup_datetime' => date('Y-m-d', strtotime($invoice->PickupDate)) . ' ' . $pickupTime[1] . ':00',
            'customer_email' => $invoice->members->EmailAddress,
            'customer_username' => $invoice->members->FirstName . ' ' . $invoice->members->LastName,
            'customer_phone' => $invoice->members->Phone,
            'customer_address' => $address,
            'job_delivery_datetime' => date('Y-m-d', strtotime($invoice->DeliveryDate)) . ' ' . $deliveryTime[1] . ':00',
            'has_pickup' => "1",
            'has_delivery' => "1",
            'layout_type' => "0",
            'timezone' => env("TOOKAN_TIMEZONE"),
            'custom_field_template' => "",
            'meta_data' => array(),
            'tracking_link' => "1",
            'notify' => "1",
            'geofence' => "0"
        );
        $url = self::URL . "create_task";
        $response = self::request($url, json_encode($tookanArray));
        return $response;
    }

    public static function update($invoice) {

        $tookanResponse = json_decode($invoice->TookanResponse);
        $data = $tookanResponse->data;
        
        if(!isset($data->pickup_job_id)){
            return false;
        }
        $jobId = $data->pickup_job_id;
        $jobDeliveryId = $data->delivery_job_id;

        $pickupTime = explode("-", $invoice->PickupTime);
        $deliveryTime = explode("-", $invoice->DeliveryTime);

        $description = "";

        if (count($invoice->services) > 0) {

            $i = 1;
            foreach ($invoice->services as $value) {
                $description .= '' . ($i) . ' # Service : ' . $value->Title . '';
                $description .= '# Quantity : ' . $value->Quantity . '';
                $description .= '# Price : ' . $value->Price . '';
                $description .= '# Total : ' . $value->Total . '';
                $i++;
            }
        }

        $address = $invoice->BuildingName . ', ' . $invoice->StreetName . ', ' . $invoice->PostalCode . ', ' . $invoice->Town;

        $tookan = array(
            'api_key' => env("TOOKAN_API_KEY"),
            'order_id' => $invoice->InvoiceNumber,
            'team_id' => env("TOOKAN_TEAM_ID"),
            'auto_assignment' => "1",
            'auto_assignment' => "1",
            'job_description' => $invoice->members->OrderNotes . " - " . $description,
            'job_pickup_phone' => $invoice->members->Phone,
            'job_pickup_name' => $invoice->members->FirstName . ' ' . $invoice->members->LastName,
            'job_pickup_email' => $invoice->members->EmailAddress,
            'job_pickup_address' => $address,
            'job_pickup_datetime' => date('Y-m-d', strtotime($invoice->PickupDate)) . ' ' . $pickupTime[1] . ':00',
            'customer_email' => $invoice->members->EmailAddress,
            'customer_username' => $invoice->members->FirstName . ' ' . $invoice->members->LastName,
            'customer_phone' => $invoice->members->Phone,
            'customer_address' => $address,
            'job_delivery_datetime' => date('Y-m-d', strtotime($invoice->DeliveryDate)) . ' ' . $deliveryTime[1] . ':00',
            'has_pickup' => "1",
            'has_delivery' => "1",
            'layout_type' => "0",
            'timezone' => env("TOOKAN_TIMEZONE"),
            'custom_field_template' => "",
            'meta_data' => array(),
            'tracking_link' => "1",
            'notify' => "1",
            'geofence' => "0"
        );

        $url = self::URL . "edit_task";
        $pickupTookan = $tookan;
        $pickupTookan["job_id"] = $jobId;
        $response = self::request($url, json_encode($pickupTookan));


        $deliveryTookan = $tookan;
        $deliveryTookan["job_id"] = $jobDeliveryId;
        $responseDelivery = self::request($url, json_encode($deliveryTookan));

        $statusTookan['api_key'] = env("TOOKAN_API_KEY");
        $statusTookan['job_id'] = $jobId . "," . $jobDeliveryId;

        if ($invoice->OrderStatus == "Pending") {
            $statusTookan['job_status'] = 6;
        } elseif ($invoice->OrderStatus == "Completed") {
            $statusTookan['job_status'] = 2;
        } elseif ($invoice->OrderStatus == "Cancel") {
            $statusTookan['job_status'] = 9;
        }

        if (isset($statusTookan['job_status'])) {
            $responseStatus = self::request(self::URL . "update_task_status", json_encode($statusTookan));
        }
        return $response;
    }

    public static function request($url, $param_array = array()) {
        try {
            $header = array();
            $header[] = 'Content-Type: application/json';
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param_array);
            $res = curl_exec($ch);
            $error = curl_error($ch);
            if (!empty($error)) {
                $res = $error;
            }
            curl_close($ch);
            return $res;
        } catch (Exception $e) {
            echo $e->getMessage();
            return null;
        }
    }

}
