<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

class BuyProduct extends CI_Controller {

    
    public function __construct()
    {
        parent::__construct();
        if($this->session->userdata('id_users') == null)
        {
            die;
        }
    }
    

    public function submit()
    {
        $id = $this->input->post("id");
        $amount = $this->input->post("amount");
        $code = $this->input->post('code');

        if($id != null && $amount != null)
        {
            $this->db->where('id_users', $this->session->userdata('id_users'));
            $query = $this->db->get('users', 1);
            $users = $query->row_array();

            $this->db->where('id_product', $id);
            $query = $this->db->get('product', 1);
            $product = $query->row_array();
            $this->load->helper('string');
            if($code != null)
            {
                $this->db->where('code', $code);
                $query = $this->db->get('discount', 1);
                if($query->num_rows() == 1)
                {
                    $discount = $query->row_array();
                    if($product['id_cate'] == $discount['id_cate'])
                    {
                        $this->db->where('id_discount', $discount['id_discount']);
                        $this->db->where('id_users', $this->session->userdata('id_users'));
                        $query = $this->db->get('logbuyproduct');
                        if($query->num_rows() < $discount['count'])
                        {
                            $realprice = $product['price'];
                            $price = ($product['price']-$product['discount'])*$amount;
                            if($price > $discount['minimumn'])
                            {
                                $totaldiscount = ($price*$discount['discount'])/100;
                                $price = $price-$totaldiscount;
                            }else{
                                echo json_encode(['status' => 0, 'msg' => 'ยอดการสั่งซื้อของคุณไม่ถึงขั้นต่ำของโค้ดส่วนลด']);
                                die;
                            }
                        }else{
                            echo json_encode(['status' => 0, 'msg' => 'คุณได้ใช้โค้ดส่วนลดตามที่กำหนดแล้ว']);
                            die;
                        }
                    }else{
                        echo json_encode(['status' => 0, 'msg' => 'โค้ดส่วนลดนี้ไม่สามารถใช้กับหมวดหมู่นี้ได้']);
                        die;
                    }
                   
                }else{
                    echo json_encode(['status' => 0, 'msg' => 'ไม่พบโค้ดส่วนลดนี้']);
                    die;
                }
            }else{
                $realprice = $product['price'];
                $price = ($product['price']-$product['discount'])*$amount;
                $totaldiscount = $product['discount'];
            }
            
            if($users['credit'] >= $price)
            {
                $this->db->where('id_product', $id);
                $this->db->where('used', 0);
                $query = $this->db->get('code', $amount);
                if($query->num_rows() == $amount)
                {
                    $textfile = '';
                    foreach($query->result_array() as $data)
                    {
                        $update[] = array(
                            'id_code'   =>  $data['id_code'],
                            'used'      =>  1
                        );
                        $textfile .= $data['text']."\r\n";
                    }
                    $filename = random_string('alpha',15);
                    $this->load->helper('file');
                    if ( ! write_file(FCPATH.'/order/order_'.$filename.'.txt', $textfile))
                    {
                        echo json_encode(['status' => 0, 'msg' => 'เกิดข้อผิดพลาดกรุณาลองใหม่ภายหลัง']);
                    }
                    else
                    {
                        if($code != null)
                        {
                            $iddiscount = $discount['id_discount'];
                        }else{
                            $iddiscount = null;
                        }
                        
                        $this->db->update_batch('code', $update,'id_code');
                        $object = array(
                            'name'  =>  $filename,
                            'product'   =>  $product['name_pro'],
                            'amount'    =>  $amount,
                            'id_users'  =>  $this->session->userdata('id_users'),
                            'total'     =>  $realprice,
                            'discount'  =>  $totaldiscount,
                            'id_discount'   => $iddiscount 
                        );
                        $this->db->insert('logbuyproduct', $object);
                        $detail = array();
                        foreach($query->result_array() as $data)
                        {
                            $detail[] = array(
                                'id_log'    =>  $this->db->insert_id(),
                                'id_code'   =>  $data['text'],    
                            );
                        }
                        $this->db->insert_batch('detail_buy', $detail);
                        
                        $this->db->query("UPDATE product SET stock = stock-$amount WHERE id_product = $id");
                        $id = $this->session->userdata('id_users');
                        $this->db->query("UPDATE users SET credit = credit-$price WHERE id_users = $id");
                        $this->session->set_userdata('credit', $this->session->userdata("credit")-$price);
                        echo json_encode(['status' => 1, 'msg' => 'ซื้อสินค้าเสร็จสิ้น']);
                    }
                }else{
                    echo json_encode(['status' => 0, 'msg' => 'สินค้าไม่เพียงพอกรุณาแก้ไขจำนวนสินค้า']);
                }
            }else{
                echo json_encode(['status' => 0, 'msg' => 'ยอดเครดิตของคุณไม่เพียงพอ']);
            }
        }else{
            echo json_encode(['status' => 0, 'msg' => 'กรุณากรอกจำนวนสินค้า']);
        }
    }
}

/* End of file BuyProduct.php */
