<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\CategoryModel;
use App\Models\GoodModel;
use App\Models\CartModel;
use App\Models\SaleModel;
use App\Models\SaleItemModel;


use Config\Database;

class Sale extends BaseController
{


    private $CategoryModel;
    private $GoodModel;
    private $CartModel;
    private $SaleModel;
    private $SaleItemModel;

    public function __construct()
    {

        $this->CategoryModel    = new CategoryModel();
        $this->GoodModel        = new GoodModel();   
        $this->CartModel        = new CartModel();   
        $this->SaleModel        = new SaleModel();   
        $this->SaleItemModel    = new SaleItemModel();   
    }

    public function index()
    {
    

        $data   = [
            'title'     => "Penjualan",
            'category'  => $this->CategoryModel->findAll()
        ];

        return view('app/sale/main/header').
        // view('templates/sidebar').
        // view('templates/topbar').
        view('app/sale/main/css-style').
        view('app/sale/main/sale-main-css', $data) .
        view('app/sale/main/sale-main', $data) .
        view('app/sale/main/sale-main-js', $data) .
        view('app/sale/main/js-script').
        view('app/sale/main/footer');

    }



    public function cart()
    {
    

        $data   = [
            'title'     => "Keranjang",
        ];

        return view('app/sale/cart/header').
        view('app/sale/cart/css-style').
        view('app/sale/cart/sale-cart-css', $data) .
        view('app/sale/cart/sale-cart', $data) .
        view('app/sale/cart/sale-cart-js', $data) .
        view('app/sale/cart/js-script').
        view('app/sale/cart/footer');

    }


    public function addToCart()
    {
        $request = json_decode(json_encode($this->request->getPOST()));

        if($this->_exitsInCart($request->id)){

            $this->CartModel->set('quantity', 'quantity+'. 1 , FALSE);
            $this->CartModel->set('total', 'total + product_price', FALSE);
            $this->CartModel->set('updated_by',session()->get('id'));
            $this->CartModel->set('updated_at',date('Y-m-d H:i:s'));
            $this->CartModel->where('user_id',session()->get('id'));
            $this->CartModel->where('product_id',$request->id);
            if(!$this->CartModel->update()){
                return $this->response->setJSON([
                    'code'      => 200,
                    'success'   => false,
                    'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
                ]);
            }

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => true,
                'message'   => "Data berhasil disimpan"
            ]);


        }else{

            $data = [
                'user_id'     => session()->get('id'),
                'product_id'     => $request->id,
                'product_name'     => $request->name,
                'product_price_buy'     => $request->price_buy,
                'product_price_sale'     => $request->price_sale,
                'product_discount'     => $request->discount,
                'product_price'     => $request->price,
                'quantity'     => 1,
                'total'     => $request->price,
                'created_by'     => session()->get('id'),
                'created_at'     => date('Y-m-d H:i:s'),
            ];

            if(!$this->CartModel->insert($data)){
                return $this->response->setJSON([
                    'code'      => 200,
                    'success'   => false,
                    'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
                ]);
            }

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => true,
                'message'   => "Data berhasil disimpan"
            ]);

        }

    }


    private function _exitsInCart($productId)
    {

        $this->CartModel->select('id');
        $this->CartModel->where('user_id',session()->get('id'));
        $this->CartModel->where('product_id',$productId);
        $row = $this->CartModel->first();

        return !empty((array) $row) ? true : false;


    }



    public function add()
    {

        $data = [
            'title' => "Tambah Kategori"
        ];

        return  view('app/category/add/category-add-css', $data) .
        view('app/category/add/category-add', $data) .
        view('app/category/add/category-add-js', $data);
    }


    public function detail($id = null)
    {


        $this->GoodModel->select('tbl_good.*, tbl_area.name AS area_name');
        $this->GoodModel->join('tbl_area','tbl_area.id=tbl_good.area_id');
        $row = $this->GoodModel->find($id);


        $data = [
            'title' => "Detail Barang",
            'code'  => $row->unique_id
        ];

        return  view('app/good/detail-qrcode/detail-qrcode-css', $data) .
        view('app/good/detail-qrcode/detail-qrcode', $data) .
        view('app/good/detail-qrcode/detail-qrcode-js', $data);
    }

    public function save()
    {

        $request    = json_decode(json_encode($this->request->getPOST()));
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required'   => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ],
        ];


        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }

            

        $data = [
            'name'    => $request->name,
            'created_by'    => session()->get('id'),
            'created_at'    => date('Y-m-d H:i:s'),
        ];

        if(!$this->CategoryModel->insert($data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);





    }


    public function getAllData()
    {
        
        $this->CategoryModel->draw     = $this->request->getPOST('draw');
        $this->CategoryModel->start    = $this->request->getPOST('start');
        $this->CategoryModel->limit    = $this->request->getPOST('length');
        $this->CategoryModel->search   = $this->request->getPOST('search')['value'];
        $this->CategoryModel->columns  = $this->request->getPOST('columns');
        $this->CategoryModel->order    = $this->request->getPOST('order');

        echo $this->CategoryModel->getAllData();
    }

    public function delete()
    {

        $request;
        if ($this->request->hasHeader('Content-Type') && strpos($this->request->getHeaderLine('Content-Type'), 'application/json') !== false) {
            $request    = $this->request->getJSON();
        }else{
            $request    = $this->request->getPOST();
        }

        $request = json_decode(json_encode($request));


        $this->CategoryModel->where('id', $request->id);
        if(!$this->CategoryModel->delete()){

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal dihapus. pastikan anda terkoneksi dengan internet"
            ]);
        }

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil dihapus"
        ]);

    }


    public function edit($id = null)
    {


        $row = $this->CategoryModel->find($id);

        $data = [
            'title' => "Edit Kategori",
            'row'   => $row
        ];

        return  view('app/category/edit/category-edit-css', $data) .
        view('app/category/edit/category-edit', $data) .
        view('app/category/edit/category-edit-js', $data);
        
    }



    public function update()
    {

        

        $request    = json_decode(json_encode($this->request->getPOST()));
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required'   => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ]
        ];


        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }
            

        
        $data = [
            'name'          => $request->name,
            'updated_by'         => session()->get('id'),
            'updated_at'         => date('Y-m-d H:i:s'),
        ];

        if(!$this->CategoryModel->update($request->id, $data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);


    }



    public function getAllCategoryName()
    {
        $page  = $this->request->getPOST('page') ? $this->request->getPOST('page') - 1 : 0;
        $limit = $this->request->getPOST('limit') ? $this->request->getPOST('limit') : 30;

        $this->CategoryModel->name          = $this->request->getPOST('name');
        $this->CategoryModel->limit         = $limit;
        $this->CategoryModel->start         = ($page * $limit);

        echo $this->CategoryModel->getAllCategoryName();
    }


    public function getAllProduct()
    {


        $this->GoodModel->search     = $this->request->getPOST('keyword');
        $this->GoodModel->startData    = $this->request->getPOST('start');
        $this->GoodModel->limitData    = $this->request->getPOST('limit');
        $this->GoodModel->type    = $this->request->getPOST('type');
        $this->GoodModel->category    = $this->request->getPOST('category');

        echo json_encode($this->GoodModel->getAllProduct());

    }


    public function getAllCart()
    {


        $this->CartModel->select('tbl_cart.*, tbl_good.image');
        $this->CartModel->join('tbl_good','tbl_good.id=tbl_cart.product_id', 'left');
        $this->CartModel->where('user_id',session()->get('id'));
        $results = $this->CartModel->findALl();

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Successfully",
            'data'      => $results
        ]);

    }

    public function changeQuantity()
    {

        $request = json_decode(json_encode($this->request->getPOST()));

        if(intval($request->quantity)<=0){

            $this->CartModel->where('id',$request->id);
            if(!$this->CartModel->delete()){
                return $this->response->setJSON([
                    'code'      => 200,
                    'success'   => false,
                    'message'   => "Produk gagal dihapus. pastikan anda terkoneksi dengan internet"
                ]);
            }

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => true,
                'message'   => "Produk berhasil dihapus"
            ]);


        }else{
                

            $this->CartModel->set('quantity', $request->quantity);
            if(strtoupper($request->type)=="PLUS"){
                $this->CartModel->set('total', 'total + product_price', FALSE);
            }else{
                $this->CartModel->set('total', 'total - product_price', FALSE);
            }
            $this->CartModel->set('updated_by',session()->get('id'));
            $this->CartModel->set('updated_at',date('Y-m-d H:i:s'));
            $this->CartModel->where('id',$request->id);
            if(!$this->CartModel->update()){
                return $this->response->setJSON([
                    'code'      => 200,
                    'success'   => false,
                    'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
                ]);
            }

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => true,
                'message'   => "Data berhasil disimpan"
            ]);

        }


    }


    public function createOrder()
    {
        $request = json_decode(json_encode($this->request->getPOST()));
        
        $discount = NULL;
        if(isset($request->discount)&&!empty($request->discount)){

            $discount = $request->discount;
        }


    
        $this->CartModel->select('tbl_cart.*');
        $this->CartModel->where('user_id',session()->get('id'));
        $carts = $this->CartModel->findALl();        
        if(count($carts)<=0){

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Keranjang kamu masih kosong"
            ]);
   
        }


        $subTotal = $this->_calculateSubTotal($carts);
        if(!empty($discount)){
            if($discount > $subTotal){

                return $this->response->setJSON([
                    'code'      => 200,
                    'success'   => false,
                    'message'   => "Diskon tidak boleh lebih besar dari total belanja"
                ]);
            }
        }


        $changeMoney = 0;
        if(isset($request->moneyPay)&&!empty($request->moneyPay)){
            $changeMoney = $request->moneyPay;
        }

        if($changeMoney<=0){

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Total uang yang dibayarakan tidak boleh kosong"
            ]);
   
        }


        $grandTotal = $subTotal - ($discount ?? 0);
        if($changeMoney<$grandTotal){

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Nominal pembayaran tidak boleh kurang dari total belanja"
            ]);

        }


        $note = [];
        $db = Database::connect();
        $db->transBegin();  
        try {

            foreach($carts AS $cart){

                $good = $this->GoodModel->find($cart->product_id);
                
                if(!empty((array)$good)){

                    if($good->stock<$cart->quantity){
                        throw new \Exception("Stok pada produk $good->name tidak mencukupi");
                    }

                    $this->GoodModel->set('stock','stock - '. intval($cart->quantity) , FALSE);
                    $this->GoodModel->where('id',$cart->product_id);
                    if(!$this->GoodModel->update()){
                        throw new \Exception("Data gagal disimpan pastikan anda terkoneksi dengan internet");
                    }

                

                }else{

                    throw new \Exception("Produk $cart->product_name tidak di temukan");

                }

            }


            $data = [
                'user_id'       => session()->get('id'),
                'subtotal'      => $subTotal,
                'discount'      => $discount,
                'grandtotal'    => $grandTotal,
                'changemoney'   => $changeMoney,
                'returnmoney'   => intval($changeMoney) - intval($grandTotal),
                'created_by'    => session()->get('id'),
                'created_at'    => date('Y-m-d H:i:s')
            ];
            
            if(!$this->SaleModel->insert($data)){

                throw new \Exception("Data gagal disimpan pastikan anda terkoneksi dengan internet");
            }

            $note = $data;
            $note['items'] = [];
            $saleId = $this->SaleModel->insertId();

            foreach ($carts as $cart) {
                $item = [
                    'sale_id'       => $saleId,
                    'product_id'    => $cart->product_id,
                    'product_name'    => $cart->product_name,
                    'product_price_buy'    => $cart->product_price_buy,
                    'product_price_sale'    => $cart->product_price_sale,
                    'product_discount'    => $cart->product_discount,
                    'product_price'    => $cart->product_price,
                    'quantity'    => $cart->quantity,
                    'total'    => $cart->total,
                    'created_by'    => session()->get('id'),
                    'created_at'    => date('Y-m-d H:i:s')
                ];

                if(!$this->SaleItemModel->insert($item)){

                    throw new \Exception("Data gagal disimpan pastikan anda terkoneksi dengan internet");
                }

                $note['items'][] = $item;

            }


            $this->CartModel->where('user_id',session()->get('id'));
            if(!$this->CartModel->delete()){
                throw new \Exception("Data gagal disimpan pastikan anda terkoneksi dengan internet");
            }


            $db->transCommit();
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => true,
                'message'   => "Pesanan berhasil dibuat",
                'data'      => $note
            ]);

            

        } catch (\Exception $e) {
            
            $db->transRollback();
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => $e->getMessage()]);
        }



    }


    private function _calculateSubTotal($carts)
    {


        if(count($carts)<1){
            return 0;
        }

        $subTotal = 0;
        foreach($carts AS $cart)
        {

            $subTotal += (intval($cart->product_price)*intval($cart->quantity));

        }

        return $subTotal;


    }



}

