<?php

class CartHandler {
    private $config;
    private $cart;

    public function __construct() {
        $this->config = $this->setConfig();
        $this->cart = $this->prepareCart();
    }

    private function setConfig() {
        return array(
            'partner' => 'C6F2E6BE',
            'idFunnel' => 6,
            'domain' => 'https://fitness.digimag99.com',
            'apiKey' => 'LsxuMz7mjj',
            'apiToken' => 'VEd3eVlYZEtPV04yU1dwMVRWRkZOQT09',
            'apiEndpoint' => 'https://iq.digimag99.com/api/checkout/',
            'sk' => 'c7dNdseyjGJ5hn10ZoBCU6YYKjRwWP7y'
        );
    }

    private function encryptData($data) {
        $sk = $this->config['sk'];
        if (function_exists('openssl_encrypt')) {
            return openssl_encrypt($data, "AES-128-ECB", md5($sk));
        }
        return $data;
    }

    private function detectIp() {
        foreach ([
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'
        ] as $key) {
            if (!empty(getenv($key))) {
                return strtok(getenv($key), ',');
            }
        }
        return 'UNKNOWN';
    }

    private function prepareCart() {
        $cart = new stdClass();
        $cart->funnel = (object) [
            'id' => $this->config['idFunnel'],
            'domain' => $this->config['domain'],
            'step' => 1,
            'path' => '',
            'pageType' => "upsellPage1"
        ];
        $cart->person = (object) [
            'sid' => session_id(),
            'ipv6' => $this->detectIp(),
            'address' => (object) [
                'billing' => new stdClass(),
                'shipping' => new stdClass()
            ],
            'payment' => (object) [
                'creditcard' => new stdClass()
            ]
        ];
        $cart->tracking = (object) [
            'pageUrl' => $_SERVER['REQUEST_URI'],
            'userAgent' => $_SERVER['HTTP_USER_AGENT'],
            'referrerUrl' => $_SERVER['HTTP_REFERER']
        ];
        $cart->affiliate = (object) [
            'affiliate' => $this->config['partner'],
            'click' => ''
        ];
        $cart->credentials = (object) [
            'key' => $this->config['apiKey'],
            'token' => $this->config['apiToken']
        ];
        return $cart;
    }

    public function setCustomerDetails($email, $billing, $shipping, $payment) {
        $this->cart->person->email = $email;
        $this->cart->person->address->billing = (object) $billing;
        $this->cart->person->address->shipping = (object) $shipping;
        $this->cart->person->payment->creditcard = (object) [
            'code' => $this->encryptData($payment['code']),
            'type' => $payment['type'],
            'year' => $payment['year'],
            'month' => $payment['month'],
            'number' => $this->encryptData($payment['number'])
        ];
    }

    public function attachAffiliate($affiliate) {
        $this->cart->affiliate->affiliateSub1 = $affiliate['sub1'];
        $this->cart->affiliate->affiliateSub2 = $affiliate['sub2'];
        $this->cart->affiliate->affiliateSub3 = $affiliate['sub3'];
    }

    public function addItem($id, $qty) {
        $this->cart->items = (object) [['id' => $id, 'qty' => $qty]];
    }

    public function transmitCart() {
        $endpoint = $this->config['apiEndpoint'];
        $ch = curl_init($endpoint);
        $payload = json_encode($this->cart);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function processResult($result) {
        if (!is_null($result)) {
            $result = json_decode($result);
        }

        if (isset($result->cart) && isset($result->cart->idCart)) {
            return [
                'status' => 'Success!',
                'title' => 'Order Number',
                'content' => $result->cart->crmOrderId
            ];
        } else {
            $errors = (array) $result->errors;
            print_r($errors);
            return [
                'status' => 'Failed!',
                'title' => 'Please review errors:',
                'content' => implode(',', $errors)
            ];
        }
    }

    public function getOrderDate() {
        return date('F d, Y');
    }
}