Uname:Linux EDL-STRETCH 4.19.0-27-amd64 #1 SMP Debian 4.19.316-1 (2024-06-25) x86_64

403WebShell
403Webshell
Server IP : 188.114.96.2  /  Your IP : 104.23.197.230
Web Server : Apache/2.4.59 (Debian)
System : Linux EDL-STRETCH 4.19.0-27-amd64 #1 SMP Debian 4.19.316-1 (2024-06-25) x86_64
User : edlftp ( 1002)
PHP Version : 7.4.33
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/nicolasj/www/sms.formationlangues.be/application/controllers/FO/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /home/nicolasj/www/sms.formationlangues.be/application/controllers/FO/Shop.php
<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Shop extends NS_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('generator');
        $this->load->helper('view');

        $this->load->model('crud_model');
        $this->load->model('shop_model');
        $this->load->model('users_model');
        $this->load->model('email_model');
        $this->load->model('event_model');
        $this->load->model('fidelity_model');
        $this->load->model('customer_model');
        $this->load->model('wallet_model');
        $this->load->model('product_transaction_model');
        $this->load->model('archive_model');

        $this->load->database();
        $this->load->library('session');

        /* cache control */
        $this->output->set_header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
        $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
        $this->output->set_header('Pragma: no-cache');
        $this->output->set_header("Expires: Mon, 26 Jul 2010 05:00:00 GMT");
    }


    public function index()
    {
        $course_list = $this->shop_model->get_courses();
        $filters = $this->shop_model->get_filters();
        $course_lang = $this->crud_model->get_languages();
        $data = array(
          "course_list" => $course_list,
          "filters" => $filters,
          "course_lang" => $course_lang,
        );

        $this->load->view('frontend/shop', $data);
    }

    public function get_signature()
    {
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        $signature = "";
        $browsers = array(
                        array("IE", "Microsoft Internet Explorer"),
                        array("Chrome", "Google Chrome"),
                        array("Firefox", "Mozzila Firefox"),
                        array("Opera", "Opera"),
                        array("Safari", "Apple Safari")
                    );

        foreach ($browsers as $browser) {
            if (strpos($userAgent, $browser[0]) !== false) {
                $signature = $signature.",".$browser[1];
            }
        }

        if (!empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
            return md5($_SERVER["HTTP_CF_CONNECTING_IP"]."+".$signature);
        }
        return md5($_SERVER['REMOTE_ADDR']."+".$signature);
    }

    public function hybrid()
    {
        $p_filters = $_POST['filters'];
        if (isset($p_filters) && $p_filters  != null) {
            $course_list = $this->shop_model->get_courses($p_filters);
        } else {
            $course_list = $this->shop_model->get_courses();
        }

        $course_visible = 0;
        foreach ($course_list as $key => $course) {
            if ($course['Course_Visibility'] == 1) {
                $course_visible++;
            }
        }

        $filters = $this->shop_model->get_filters();
        $course_lang = $this->crud_model->get_languages();
        $data = [
            "course_visible" => $course_visible,
            "course_list" => $course_list,
            "filters" => $filters,
            "course_lang" => $course_lang,
        ];

        $this->load->view('frontend/shop-hybrid', $data);
    }

    public function loadData()
    {
        $p_filters = $_POST['filters'];

        if (strpos($p_filters, ",") !== false) {
            $filters = $p_filters;
        } elseif (!is_array($p_filters)) {
            $filters = $p_filters;
        } else {
            $filters = implode(',', $p_filters);
        }

        if ($filters != null) {
            $course_list = $this->shop_model->get_courses($filters);
            foreach ($course_list as $key => $course) {
                $this->load->view('frontend/shop/product/product', $course);
            }
        }
    }

    public function loadCart()
    {
        $data = $this->cartStatus('ctrlr');
        $products = json_decode($data['Cart'], true);

        foreach ($products as $key => $product) {
            $data =	is_array($product['data']) ? $product['data'] : json_decode($product['data'], true);
            $data['origin'] = "cart";
            $data['qty'] = $product["qty"];
            $productDB = $this->shop_model->get_course($data["Course_ID"]);

            $data['Price_HTVA'] =  $productDB['Price_HTVA'];
            $data['Price_TVA'] = $productDB['Price_TVA'];
            $data['Price_HTVA_Promo'] = $productDB['Price_HTVA_Promo'];
            $data['Price_TVA_Promo'] = $productDB['Price_TVA_Promo'];
            
            $data['CourseVat'] = $productDB['CourseVat'];

            $this->load->view('frontend/shop/product/product', $data);
        }
    }

    public function loadCheckout()
    {
        $this->load->view('/frontend/shop/cart/checkout.php');
    }

    public function product_number($cart)
    {
        $qty = 0;
        foreach ($cart as $key => $product) {
            $qty = $qty + $product['qty'];
        }
        return $qty;
    }

    public function cart()
    {
        $user_id = $this->session->userdata('userID');
        $customer_id = $this->session->customer_id;
        $stripe_error = null;

        $payment_methods = ['card','bancontact'];

        $this->updateCart();
        $data = $this->cartStatus('ctrlr'); //SLOW !!

        try {
            $stripe = new \Stripe\StripeClient($this->config->item('stripe_secret_pro'));

            if ($data['Cart_Total_Promo'] != '' && $data['Cart_Total_Promo'] > 0) {
                $total = (int) $data['Cart_Total_Promo'];
            } else {
                $total = (int) $data['Cart_Total'];
            }

            if ($total > 0) {
                /* Alma require a min total of 50.00€ or return an error */
                if ($total > 51 * 100) {
                    $payment_methods[] = 'alma';
                }
                $payment_intent = $stripe->paymentIntents->create([
                    'amount' => ($total * 100),
                    'currency' => 'eur',
                    'payment_method_types' => $payment_methods,
                ]);

                $data['stripe_client_secret'] = $payment_intent->client_secret;
            }
        } catch(\Stripe\Exception\CardException $e) {
            $stripe_error = "A payment error occurred: {$e->getError()->message}. (request id: {$e->getRequestId()})";
        } catch (\Stripe\Exception\InvalidRequestException $e) {
            $stripe_error = "An invalid request occurred. (request id: {$e->getRequestId()})";
        } catch (Exception $e) {
            $stripe_error = 'Another problem occurred, maybe unrelated to Stripe.';
        }

        if (!empty($customer_id)) {
            $data['customer'] = $this->customer_model->get_customer_payment_unfinish((int) $customer_id);
        }
        if (empty($data['customer']) && !empty($user_id)) {
            $user = $this->users_model->get_entry((int) $user_id);
            $data['customer'] = [
                'Name' => $user->first_name,
                'Surname' => $user->last_name,
                'Mail' => $user->email,
                'Phone' => $user->phone,
                "Browser" => $_SERVER['HTTP_USER_AGENT'],
                "History" => $url,
            ];
        }

        $data['flash_error'] = $this->session->flashdata('error_payment');
        if ($stripe_error) {
            $data['flash_error'] = !empty($data['flash_error']) ? $data['flash_error'] . '<br >' . $stripe_error : $stripe_error;
        }

        $this->load->view('frontend/shop/cart', $data);
    }

    /**
     * Return url for Stripe.
     * Process payment status
     *
     * @return void
     */
    public function return_payment()
    {
        $payment_intent_id = $this->input->get('payment_intent');
        $stripe_client_secret = $this->input->get('payment_intent_client_secret');
        $customer_id = $this->session->customer_id;
        $customer = $this->customer_model->get_customer_payment_unfinish((int) $customer_id);

        if (!empty($customer) && $customer['stripe_client_secret'] === $stripe_client_secret) {
            $stripe = new \Stripe\StripeClient($this->config->item('stripe_secret_pro'));
            $payment_intent = $stripe->paymentIntents->retrieve($payment_intent_id, []);

            // Update customer
            $this->customer_model->update_entry((int) $customer_id, [
                'Payment_ID'    => $payment_intent_id,
                'Payment_State' => $payment_intent->status
            ]);

            if ($payment_intent->status === "succeeded") {
                return $this->payment_process($payment_intent->status, $payment_intent_id, $customer_id);
            }
        }

        $this->session->set_flashdata('error_payment', 'La paiement a échoué. Veuillez recommencer ou contacter notre service client.');
        return $this->redirect(base_url() . 'shop/cart');
    }

    public function save_customer()
    {
        $errors = [];

        $user_id = $this->session->userdata('userID');
        $user = null;
        if (!empty($user_id)) {
            $user = $this->users_model->get_entry((int) $user_id);
        }

        $first_name = $this->input->post('first_name');
        $last_name = $this->input->post('last_name');
        $mail = $this->input->post('email');
        $phone = $this->input->post('phone');
        $add_street = $this->input->post('address_street');
        $add_city = $this->input->post('address_city');
        $add_code = $this->input->post('address_code');

        $payment_id = $this->input->post('Payment_ID');
        $payment_state = $this->input->post('Payment_State');
        $stripe_client_secret = !empty($this->input->post('stripe_client_secret')) ? $this->input->post('stripe_client_secret') : null;

        $customer_id = $_SESSION['customer_id'];
        $customer = $this->customer_model->get_customer_payment_unfinish((int) $customer_id);

        if (empty($mail) || !filter_var($mail, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Please provide a valid email address';
        } else if ($this->users_model->email_exist($mail) && $user->email !== $mail) {
            $errors[] = 'This mail is already registred. You must <a href="/login/r/?callback=cart">log in</a> before you can continue your payment.';
        }
        if (!$this->users_model->check_address($add_street, '', 'belgium', $add_city, $add_code)) {
            $errors[] = "Please provide a correct address";
        }

        if (!empty($errors)) {
            echo json_encode(['success' => false, 'msg' => $errors]);
            return;
        }

        $ip = !empty($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER['REMOTE_ADDR'];

        $logged_user = null;
        $logged_in = false;
        if (isset($_SESSION['userID'])) {
            $logged_user = $_SESSION['userID'];
            $logged_in = true;
        }
        $url = base_url() . $_SERVER["REQUEST_URI"];

        $customer_data = array(
            'Name' => $first_name,
            'Surname' => $last_name,
            'Mail' => $mail,
            'Add_Street' => $add_street,
            'Add_City' => $add_city,
            'Add_Code' => $add_code,
            'Phone' => $phone,
            "IP" => $ip,
            "Payment_ID" => $payment_id,
            "Payment_State" => $payment_state,
            "Logged_User" => $logged_user,
            "Logged_In" => $logged_in,
            "Browser" => $_SERVER['HTTP_USER_AGENT'],
            "History" => $url,
            'stripe_client_secret' => $stripe_client_secret,
            "Session" => json_encode($_SESSION),
        );

        if (!empty($customer_id) && !empty($customer)) {
            //update

            $id_customer = (int) $_SESSION['customer_id'];
            $history = $this->db->get_where('customer', array('ID' => $id_customer))->result_array()[0]['History'];

            if (is_array($payment_state)) {
                $payment_state = implode(';', $payment_state);
            }

            $customer_data['History'] = "$history>> $url";
            $customer_data['Payment_State'] = $payment_state;

            $this->db->where('ID', $id_customer);
            $this->db->update('customer', $customer_data);

            $this->db->where('Signature', $this->get_signature());
            $this->db->update('shop_session', array('Linked_User' => $id_customer));

            echo json_encode(['success' => true]);
            return;
        } else {
            //create

            $this->db->insert('customer', $customer_data);

            $id_customer = $this->db->insert_id();
            $_SESSION['customer_id'] = (int) $id_customer;

            $this->db->where('Signature', $this->get_signature());
            $this->db->update('shop_session', array('Linked_User' => $id_customer));

            echo json_encode(['success' => true]);
            return;
        }

        echo json_encode(['success' => false]);
        return;
    }

    public function cart_restore()
    {
    }

    public function initialize_cart()
    {
        $user = $this->session->userdata('userID');

        if (isset($user)) {
            $data = array(
              'State' => '',
              "IP" => !empty($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER['REMOTE_ADDR'],
              "Signature" => $this->get_signature()
            );
            $this->db->set($data);
            $this->db->where(array('Linked_User' => $user,'State' => 'generated'));
            $this->db->update('shop_session');

            header("Location: /shop/cart");
            exit();
        } else {
            $_SESSION['initialize_cart'] = true;
            header("Location: /login#init_cart");
            exit();
        }
    }

    public function cartStatus($o = "tmpl")
    {
        $query = "SELECT * FROM shop_session 
                  WHERE `Signature` = '{$this->get_signature()}' 
                  AND (`State` = '' OR `State` IS NULL)
                  ORDER BY `ID` DESC";

        $sessionCart = $this->db->query($query)->result_array();
        unset($sessionCart[0]['Linked_User']);
        if ($o == "tmpl") {
            echo json_encode($sessionCart);
        }

        return $sessionCart[0];
    }

    public function get_unpaid_shop_session(): array
    {
        $query = "SELECT * FROM shop_session 
                  WHERE `Signature` = '{$this->get_signature()}' 
                  AND (`State` = '' OR `State` IS NULL)
                  ORDER BY `ID` DESC";

        $sessionCart = $this->db->query($query)->result_array();
        if (empty($sessionCart) || empty($sessionCart[0])) {
            return [];
        }
        return $sessionCart[0];
    }

    public function clear()
    {
        $this->session->unset_userdata('cart');
        echo "cleaned";
    }

    public function getProduct()
    {
        $_POST['product'];
        echo json_encode($this->shop_model->get_course($product));
    }

    private function payment_process(string $state, string $payment_id, int $customer_id)
    {
        $cart = $this->cartStatus('ctrlr');
        $customer = $this->customer_model->get_customer((int) $customer_id);
        $user_id = null;

        if (empty($cart)) {
            $_SESSION['error'] = "Cart empty";
            $this->redirect(base_url() . 'profile');
            return;
        }
        $pass = '';

        /* Create user if not exist */
        if (!isset($_SESSION['userID'])) {
            $l1 = $customer['Add_Street'];
            $country = "belgique";
            $city = $customer['Add_City'];
            $code = $customer['Add_Code'];

            $pass = $this->users_model->generate_pass(8);
            $id_address = (int) $this->users_model->create_user_address($l1, '', $country, '', $city, $code);
            $user_id = $this->users_model->create_user($customer['Mail'], $pass, $customer['Name'], $customer['Surname'], $customer['Phone'], '6', '1', '3', '1', '1');

            $this->email_model->account_opening_email('en', 'invited', $firstname." ".$lastname, $mail, $pass, $user_id);
            $this->event_model->trigger_user('Profile_Creation_invited', 'en', $user_id, $pass);
        } else {
            $user_id = (int) $_SESSION['userID'];
            $guest_address = $this->crud_model->guess_user_address($user_id);
            $id_address = !empty($guest_address['address_id']) ? (int) $guest_address['address_id'] : null;
        }

        /* Send Payment Confirmation mail */
        $this->event_model->trigger_user('Shop_Successful_Payment', 'en', $user_id, $pass);

        $this->fidelity_model->check_rules($user_id);
        $this->customer_model->update_session($this->get_signature(), $user_id);

        /* Save the cart as an transaction and add courses product to users */
        $transaction_id = $this->customer_model->transaction_log($payment_id, $user_id, $id_address, $cart, $cart['Cart_Total'], $state, "done");
        $products_cart = json_decode($cart['Cart'], true);

        if (!empty($products_cart)) {
            $this->product_transaction_model->add_products_transaction((int) $transaction_id, (int) $user_id, $products_cart, 0);
        }

        if (!isset($_SESSION['userID'])) {
            /* Create user session */
            $this->session->set_userdata([
                'userID' => (int) $user_id,
                'invited_login' => '1',
                'invited_id' => (int) $user_id,
                'login_user_id' => (int) $user_id,
                'name' => $firstname . ' ' . $lastname,
                'login_type' => 'invited',
            ]);
        } else {
            $role = $_SESSION['login_type'];
            if ($role != "invited") {
                // update the balance during course assignation
                if ($this->users_model->is_paid($user_id)) {

                    if ($role == "student") {
                        $this->archive_model->unarchive_user($user_id);
                    } elseif ($role == "parent") {
                        // if cart contain multiple course_start add forach $childs
                        $jsonCart = json_decode($cart['Cart'], true);
                        $prod_n = $this->product_number($jsonCart);
                        //improved: force on pending to create student
                        $this->customer_model->update_user_state('is_final', '0', $user_id);
                        $childs = $this->crud_model->get_parent_child($user_id);

                        if (count($childs) > 1) {
                            $this->archive_model->unarchive_user($user_id);

                            foreach ($childs as $key => $child) {
                                if ($key < $prod_n) {
                                    $this->archive_model->unarchive_user($child);
                                }
                            }
                        } elseif (count($childs) == 1) {
                            $j = json_decode($data['Cart'], true);
                            $isoLang = $this->profile_model->intToIso($this->crud_model->get_user_lang($user_id));
                            $this->archive_model->unarchive_user($childs[0]);
                            foreach ($j as $key => $p) {
                                $json = json_decode(($p['data']), true)[0];
                            }
                        }
                    }
                }
            }
        }

        // Payment data for Google Tag Manager
        $this->session->set_userdata(['new_purchase' => true, 'order_id' => (int) $transaction_id, 'order_amount' => (float) $cart['Cart_Total']]);

        $this->redirect(base_url() . '/profile');
    }

    public function check_expiration($exp)
    {
        if ($exp == "0000-00-00" || $exp == " " || $exp == "") {
            return false;
        } else {
            $today = strtotime('today UTC');
            $expDate = strtotime($exp);
            if ($today >= $expDate) {
                return true;
            } else {
                return false;
            }
        }
    }

    // product action
    public function setCart()
    {
        $cart = $_POST['cart'];
        $cart_array = json_decode($cart, true);
        $cart_data = $cart_array['cart'];
        $this->session->set_userdata('cart', $cart_data);
        header('Location: https://sms.ecoledelangues.be/shop/cart');
    }

    public function restoreCart($cart)
    {
        $cart_array = json_decode($cart, true);
        $cart_data = $cart_array['cart'];
        $this->session->set_userdata('cart', $cart_data);
        header('Location: https://sms.ecoledelangues.be/shop/cart_restore');
    }

    public function addToCart($id = null, $qty = null)
    {
        $id  = empty($id) ? (int) $this->input->post('product') : $id;
        $qty = empty($qty) ? (int) $this->input->post('qty') : $qty;
        if ($id <= 0 || $qty <= 0) {
            echo json_decode(['success' => false, 'msg' => "Missing product id or quantity"]);
            return;
        }

        $course = $this->shop_model->get_course($id);
        if (empty($course)) {
            echo json_decode(['success' => false, 'msg' => "Missing course"]);
            return;
        }

        $signature = $this->get_signature();
        $shop_session = $this->get_unpaid_shop_session();

        if (!empty($shop_session)) {
            $cart = array();
            if ($shop_session['Cart'] !=  null) {
                $cart =	json_decode($shop_session['Cart'], true);
            }

            if (array_key_exists($id, $cart)) {
                $prevQty = $cart[$id]['qty'];
                $cart[$id]['qty'] = $prevQty + $qty;
            } else {
                $product_item = array(
                    'data' => $course,
                    'qty' => $qty,
                    'option' => null,
                );
                $cart[$id] = $product_item;
            }

            //resume cart data
            $cart_qty = 0;
            $cart_total = 0;
            $cart_vat = 0;
            $pro = 0;
            $pro_vat = 0;

            foreach ($cart as $product) {
                $data = $product['data'];

                $price_original = $data['Course_Price'];
                $price = $price_original;
                $target_vat = 0;
                $target_qty = (int) $product['qty'];
                $price = (float) (!empty($data['Price_TVA_Promo']) ? $data['Price_TVA_Promo'] : $data['Price_TVA']);

                // update cart data
                $cart_qty += $target_qty;
                $pro += $price * $target_qty;
                $cart_total = round($cart_total + ($price * $target_qty), 2);
            }

            //check if promo
            $cart_total_promo = 0;
            $voucher = $shop_session['Promotion'];
            $voucher_amount = (int) $voucher;
            if ($voucher != '') {
                if (strpos($voucher, "€") > -1) {
                    // Euro
                    $cart_total_promo = $cart_total - $voucher_amount;
                } elseif (strpos($voucher, "%") > -1) {
                    // Percent
                    $cart_total_promo = $cart_total - ($cart_total * $voucher_amount / 100);
                }
            }

            //UPDATE
            $this->db->where(['ID' => $shop_session['ID']]);
            $this->db->update('shop_session', [
                "Cart_Qty" => $cart_qty,
                "Cart_Total" => $cart_total,
                "Cart_Total_Promo" => round($cart_total_promo, 2),
                "Cart_Vat" => $cart_vat,
                "Pro_Total" => $pro,
                "Pro_Total_Vat" => $pro_vat,
                "Cart" => json_encode($cart),
            ]);
        } else {
            //insert
            $cart = [];
            $cart[$id] = [
                   'data' => $course,
                   'qty' => $qty,
                   'option' => null,
            ];

            //resume cart data
            $cart_qty = 0;
            $cart_total = 0;
            $cart_vat = 0;
            $pro = 0;
            $pro_vat = 0;

            foreach ($cart as $product) {
                $data = $product['data'];

                $price_original = $data['Course_Price'];
                $price = $price_original;
                $target_vat = 0;
                $target_qty = (int) $product['qty'];
                $price = (float) (!empty($data['Price_TVA_Promo']) ? $data['Price_TVA_Promo'] : $data['Price_TVA']);

                // update cart data
                $cart_qty += $target_qty;
                $pro += $price * $target_qty;
                $cart_total = round($cart_total + ($price * $target_qty), 2);
            }

            //check if promo
            $cart_total_promo = 0;
            $voucher = $shop_session['Promotion'];
            $voucher_amount = (int) $voucher;
            if ($voucher != '') {
                if (strpos($voucher, "€") > -1) {
                    // Euro
                    $cart_total_promo = $cart_total - $voucher_amount;
                } elseif (strpos($voucher, "%") > -1) {
                    // Percent
                    $cart_total_promo = $cart_total - ($cart_total * $voucher_amount / 100);
                }
            }

            $this->db->insert('shop_session', [
                "Cart_Qty" => $cart_qty,
                "Cart_Total" => $cart_total,
                "Cart_Total_Promo" => round($cart_total_promo, 2),
                "Cart_Vat" => $cart_vat,
                "Pro_Total" => $pro,
                "Pro_Total_Vat" => $pro_vat,
                "Cart" => json_encode($cart),
                "IP" => !empty($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER['REMOTE_ADDR'],
                "Signature" => $this->get_signature()
            ]);
        }
    }

    public function removeFromCart($id = null, $qty = null)
    {
        if ($id == null && $qty == null) {
            $id = $this->input->post('product');
            $qty = $this->input->post('qty');
        }

        $signature = $this->get_signature();
        $shop_session = $this->get_unpaid_shop_session();

        if (!empty($shop_session)) {

            $cart = array();
            if ($shop_session['Cart'] !=  null) {
                $cart =	json_decode($shop_session['Cart'], true);
            }

            if (array_key_exists($id, $cart)) {
                $prevQty = $cart[$id]['qty'];
                if ($qty == 'all') {
                    //remove element
                    unset($cart[$id]);
                } elseif ($prevQty > 1) {
                    $cart[$id]['qty'] = $prevQty - $qty;
                } else {
                    //remove element
                    unset($cart[$id]);
                }
            } else {
                return; //no key = nothing to do
            }

            //resume cart data
            $cart_qty = 0;
            $cart_total = 0;
            $cart_vat = 0;
            $pro = 0;
            $pro_vat = 0;
            foreach ($cart as $key => $product) {
                $data = $product['data'];

                $price_original = $data['Course_Price'];
                $price = $price_original;
                $target_vat = 0;
                $target_qty = $product['qty'];

                if ($data['Price_TVA_Promo'] == 0) {
                    $price =  $data['Price_TVA'];
                } else {
                    $price =  $data['Price_TVA_Promo'];
                }
                // update cart data
                $cart_qty = $cart_qty + $target_qty;
                $cart_vat = 0;

                $course_id = $this->shop_model->get_product_id($id);
                $pro = $pro + ($price * $target_qty);
                $cart_total = round($cart_total + ($price * $target_qty), 2);
            }

            //check if promo
            $cart_total_promo = 0;
            $voucher = $shop_session['Promotion'];
            $voucher_amount = (int) $voucher;
            if ($voucher != '') {
                if (strpos($voucher, "€") > -1) {
                    // Euro
                    $cart_total_promo = $cart_total - $voucher_amount;
                } elseif (strpos($voucher, "%") > -1) {
                    // Percent
                    $cart_total_promo = $cart_total - ($cart_total * $voucher_amount / 100);
                }
            }

            //UPDATE
            $this->db->set([
                "Cart_Qty" => $cart_qty,
                "Cart_Total" => $cart_total,
                "Cart_Total_Promo" => round($cart_total_promo, 2),
                "Cart_Vat" => $cart_vat,
                "Pro_Total" => $pro,
                "Pro_Total_Vat" => $pro_vat,
                "Cart" => json_encode($cart)
            ]);
            $this->db->where(['ID' => $shop_session['ID']]);
            $this->db->update('shop_session');

        } else {
            return; // no cart = nothing to do
        }
    }

    public function updateCart()
    {
        $signature = $this->get_signature();
        $shop_session = $this->get_unpaid_shop_session();

        if (!empty($shop_session)) {

            $cart = array();
            if ($shop_session['Cart'] !=  null) {
                $cart =	json_decode($shop_session['Cart'], true);
            }

            //resume cart data
            $cart_qty = 0;
            $cart_total = 0;
            $cart_vat = 0;
            $pro = 0;
            $pro_vat = 0;
            foreach ($cart as $key => $product) {
                $data = $product['data'];

                $price_original = $data['Course_Price'];
                $price = $price_original;
                $target_vat = 0;
                $target_qty = $product['qty'];

                if ($data['Price_TVA_Promo'] == 0) {
                    $price =  $data['Price_TVA'];
                } else {
                    $price =  $data['Price_TVA_Promo'];
                }
                // update cart data
                $cart_qty = $cart_qty + $target_qty;
                $cart_vat = 0;//$cart_vat + ($target_vat * $target_qty);
                $pro = $pro + ($price * $target_qty);
                $cart_total = round($cart_total + ($price * $target_qty), 2);
            }

            //check if promo
            $cart_total_promo = 0;
            $voucher = $shop_session['Promotion'];
            $voucher_amount = (int) $voucher;

            if ($voucher != '') {
                if (strpos($voucher, "€") > -1) {
                    // Euro
                    $cart_total_promo = $cart_total - $voucher_amount;
                } elseif (strpos($voucher, "%") > -1) {
                    // Percent
                    $cart_total_promo = $cart_total - ($cart_total * $voucher_amount / 100);
                }
            }

            //UPDATE
            $this->db->set($this->crud_model->cleanArray([
                "Cart_Qty" => $cart_qty,
                "Cart_Total" => $cart_total,
                "Cart_Total_Promo" => round($cart_total_promo, 2),
                "Cart_Vat" => $cart_vat,
                "Pro_Total" => $pro,
                "Pro_Total_Vat" => $pro_vat,
                "Cart" => json_encode($cart),
            ]));
            $this->db->where(['ID' => $shop_session['ID']]);
            $this->db->update('shop_session');
        }
    }

    public function delete()
    {
        $this->session->unset_userdata('cart');

        $query = "DELETE FROM shop_session 
                  WHERE `Signature` = ? 
                  AND (`State` = '' OR `State` IS NULL)";
        $this->db->query($query, [$this->get_signature()]);

        echo json_encode(['success' => true]);
        return;
    }

    // original from Student
    public function assignAll($studentId, $courseId, $isoLang)
    {
        //keep in mind to avoid duplicate content :√
        $last;
        $lessonsId = $this->crud_model->get_course_lessons($courseId);

        //var_dump($courseId);
        if (count($lessonsId) == 0) {
            //echo "any lessons are setted, please try again after lesson creation";
            $this->customer_model->set_preference($studentId, $courseId);
            return;
        }
        //var_dump($lessonsId);
        foreach ($lessonsId as $key => $lessonId) {
            $assigned = $this->users_model->checkAssigned($studentId, $courseId, $lessonId);
            if (isset($studentId) && isset($courseId) && isset($lessonId) && ($assigned == 'false')) {

                $sql = array(
                  'course_id' => "$courseId",
                  'lesson_id' => $lessonId["ID"],
                  'student_id' => "$studentId",
                  'author' => 'From Customer :'.$this->session->userdata('userID')
                );
                $this->db->insert('course_student_new', $this->crud_model->cleanArray($sql));
                ($this->event_model->trigger_first_lesson('Course_Student_First_Assignation', $isoLang, $studentId, $lessonId["ID"]));
            }
        }
        $this->customer_model->update_user_state('is_final', '1', $studentId);
        $this->customer_model->reset_preference($studentId, $courseId);
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit