<?php
class ControllerExtensionModuleStokuyarisi extends Controller {
	public function index() {

        $this->load->model('extension/module/stokuyarisi');

        $last_order = $this->model_extension_module_stokuyarisi->getLastOrder();
        $last_order_id = $last_order['order_id'];

        // last_order_products değişkenindeki p.quantity sütunu ürünün toplam stokudur.
        $last_order_products = $this->model_extension_module_stokuyarisi->getLastOrderProducts($last_order_id);

        if($last_order_products->num_rows>0) {

            $quantity = $this->db->query("SELECT * FROM  " . DB_PREFIX . "setting WHERE `key` = 'stokuyarisi_miktar' LIMIT 1")->row['value'];
            //$quantity = $this->config->get('stokuyarisi_miktar'); // çalışmıyor

            foreach($last_order_products->rows as $product) {
                if($product['quantity']<= (int)$quantity && $product['quantity']>0) {         
                    $products_in_cart = $this->model_extension_module_stokuyarisi->findProductInCart($product['product_id']);

                    foreach($products_in_cart->rows as $cart_item) {

                        if($cart_item['customer_id']!==0 && $cart_item['customer_id']!=$last_order['customer_id']) { //üyelik kontrolü ve siparişi veren üyeyi dışlama                           
                            $customer_email = $this->model_extension_module_stokuyarisi->getCustomerEmail($cart_item['customer_id']);
                            $uyari_history = $this->model_extension_module_stokuyarisi->getUyariHistory($cart_item['customer_id']);

                            if($uyari_history->num_rows == 0 && $customer_email) {

                                $this->model_extension_module_stokuyarisi->send($customer_email);
                                $this->model_extension_module_stokuyarisi->createUyariHistory($cart_item['customer_id'], $cart_item['product_id']);

                            }

                            $this->model_extension_module_stokuyarisi->deleteOutdatedDatas();
                        }
                    }
                }
            }
        }
	}
}