<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

use Illuminate\Http\RedirectResponse;

use App\Models\toko;
use App\Models\Cart; 
use App\Models\Order;

class OrderController extends Controller
{
    public function getDataToko($nik)
    {
        // $user = Auth::user();
    
        $dataToko = toko::where('nik', $nik)->get(); 

        if(!$dataToko) {
            return response()->json(['message' => 'Toko Tidak ditemukan'], 404);
        }
        return response()->json($dataToko);
    }

    public function getDataKategori()
    {
        //$data2 = DB::table("itemmaster")->select("salesprice_incl", "totaldisc", 'namelevel5')->distinct('namelevel5')->get();
        $dataKategori = DB::table('itemmaster') ->select('namelevel5', DB::raw('MAX(item_id) as item_id'))
        ->groupBy('namelevel5')
        ->get();

        //return response()->json($data2, 200, [], JSON_PRETTY_PRINT);
        return response()->json($dataKategori,200, [], JSON_PRETTY_PRINT);
    }

    // public function getDataKategori()
    // {
    //     $data2 = DB::select("SELECT DISTINCT (namelevel5) as namelevel5, salesprice_incl, totaldisc, name_discription FROM itemmaster");
    //     // $dataKategori = DB::table('itemmaster')
    //     // ->select('item_id','namelevel5', 'salesprice_incl', 'totaldisc', 'name_discription')
    //     // ->get()->toArray();

    //     $arr_item = [];
    //     foreach($data2 as $a){
    //         if(!in_array(['namelevel5' => $a->namelevel5], $arr_item)){
    //             $arr_item[] = [
    //                 'namelevel5' => $a->namelevel5
    //             ];
    //         }
    //     }

    //     return json_encode($data2);

    //     //return response()->json($arr_item, 200, [], JSON_PRETTY_PRINT); 
    // }


    public function getDataGambar()
    {
        $dataGambar = DB::table('imgkategori')->select('namelevel5', 'img','name')->get();
        
        // Convert blob data to base64 encoding
        $dataGambar = $dataGambar->map(function ($image) {
            return [
                'namelevel5' => utf8_encode($image->namelevel5),
                'img' => base64_encode($image->img),
                'name' => $image->name,
            ];
        });
        
        return response()->json($dataGambar, 200, [], JSON_PRETTY_PRINT);
    }

    // public function getDataProduk($namelevel5)
    // {
    //     $dataProduk = DB::table('itemmaster')
    //                     ->where('namelevel5', $namelevel5)
    //                     ->select('id', 'item_id', 'namelevel5', 'salesprice_incl', 'name_discription', 'totaldisc')
    //                     ->get();

    
    //     return response()->json($dataProduk, 200, [], JSON_PRETTY_PRINT);
    // }
    
    public function getDataProduk($namelevel5)
    {
        $accountNum = "";
        if(isset($_GET['accountnum'])){
            $accountNum = $_GET['accountnum'];
        }
        //tambahkan accountnum toko sebagai syarat untuk tarik data harga yg mendapatkan hkn atau tidak
        $dataProduk = DB::table('itemmaster')
                        ->where('namelevel5', $namelevel5)
                        ->select('id', 'item_id', 'namelevel5', 'salesprice_incl', 'name_discription', 'totaldisc')
                        ->get()->toArray();
        $data = [];
        foreach($dataProduk as $a){
            $itemToko = DB::table("itemtoko")->where('group', $a->namelevel5)->orWhere("accountnum", $accountNum)->get();
            // $itemToko = DB::select("SELECT * FROM itemtoko WHERE group='".$a->namelevel5."' or item_id='".$a->item_id."' ");
            if(count($itemToko) != 0){
                $inToko = [];
                foreach($itemToko->toArray() as $t){
                    $issetT = false;
                    if($t->item_id == $a->item_id){
                        if($t->accountnum == $accountNum){ $issetT = true; }
                        if(!empty($t->periode_end)){
                            if(date("Y-m-d") > date("Y-m-d", strtotime($t->periode_end)) ){ $issetT = false; }
                        }

                    }

                    if($issetT){
                        $inToko[] = [
                            'harga_normal' => $t->hkn,
                            'diskon' => $t->disc_max,
                            'source' => 'itemtoko',
                            'namelevel5' => $a->namelevel5,
                            'item_id' => $a->item_id,
                            'name_discription' => $a->name_discription,
                            'salesprice_incl' => floatval($t->hkn),
                            'accountnum_query' => $accountNum,
                            'accountnum_toko' => $t->accountnum
                        ];
                    }
                }
                if(count($inToko) != 0){
                    $data[] = $inToko[0];
                }else{
                    $data[] = [
                        'harga_normal' => $a->salesprice_incl,
                        'diskon' => $a->totaldisc,
                        'source' => 'itemmaster',
                        'namelevel5' => $a->namelevel5,
                        'item_id' => $a->item_id,
                        'name_discription' => $a->name_discription,
                        'salesprice_incl' => floatval($a->salesprice_incl),
                        'accountnum' => $accountNum
                    ];
                }
            }else{
                $data[] = [
                    'harga_normal' => $a->salesprice_incl,
                    'diskon' => $a->totaldisc,
                    'source' => 'itemmaster',
                    'namelevel5' => $a->namelevel5,
                    'item_id' => $a->item_id,
                    'name_discription' => $a->name_discription,
                    'salesprice_incl' => floatval($a->salesprice_incl),
                    'accountnum' => $accountNum
                ];
            }
        }

        return json_encode($data);
        //return response()->json($dataProduk, 200, [], JSON_PRETTY_PRINT);
    }
    
    public function getCountCart()
    {
        if($_GET){
            $err = "";
            if(!isset($_GET['user_id'])){ $err = "Params (user_id) is required"; }

            if($err == ""){
                $getData = DB::table("cart")->select("id")->where("user_id", $_GET['user_id'])->get()->toArray();

                $call['code'] = 200;
                $call['message'] = "Success";
                $call['data'] = [
                    'total' => count($getData)
                ];
            }else{
                $call['code'] = 400;
                $call['message'] = $err;
            }
        }else{
            $call['code'] = 400;
            $call['message'] = "Failed";
        }
        return json_encode($call);
    }

    public function inCart()
    {
        if($_POST){
            $err = "";
            if(!isset($_POST['user_id'])){ $err = "Params (user_id) is required"; }
            if(!isset($_POST['item_id'])){ $err = "Params (item_id) is required"; }
            if(!isset($_POST['namelevel5'])){ $err = "Params (namelevel5) is required"; }
            if(!isset($_POST['name_discription'])){ $err = "Params (name_discription) is required";}
            if(!isset($_POST['salesprice_incl'])){ $err = "Params (salesprice_incl) is required"; }
            if(!isset($_POST['disc'])){ $err = "Params (disc) is required";}
            if(!isset($_POST['totalharga'])){ $err = "Params (totalharga) is required";}
            if(!isset($_POST['source'])){ $err = "Params (source) is required";}
            if(!isset($_POST['accountnum'])){ $err = "Params (accountnum) is required";}
            if(!isset($_POST['namaToko'])){ $err = "Params (namaToko) is required";}
            if($err == ""){
                $cekCart = DB::select("SELECT * FROM cart WHERE user_id='".$_POST['user_id']."' ");
                $errV = "";
                foreach($cekCart as $a){
                    if($a->toko != $_POST['namaToko']){ $errV = "Toko dalam keranjang tidak boleh lebih dari 1"; }
                }
                if($errV == ""){
                    DB::insert("insert into cart (user_id, item_id, namelevel5, name_discription, salesprice_incl,disc, totalharga, source, accountnum, toko) values ('".$_POST['user_id']."', '".$_POST['item_id']."', '".$_POST['namelevel5']."', '".$_POST['name_discription']."', '".$_POST['salesprice_incl']."', '".$_POST['disc']."', '".$_POST['totalharga']."', '".$_POST['source']."', '".$_POST['accountnum']."', '".$_POST['namaToko']."')");

                    $call['code'] = 200;
                    $call['message'] = "Success";
                    $call['post'] = $_POST;
                }else{
                    $call['code'] = 400;
                    $call['message'] = $errV;
                }
            }else{
                $call['code'] = 400;
                $call['message'] = $err;
            }
        }else{ 
            $call['code'] = 400;
            $call['message'] = "Failed";
        }
        return json_encode($call);
    }

    public function getDataCart($user_id){
        $dataCart = DB::table('cart')
                    ->select('id','item_id','namelevel5', 'salesprice_incl','name_discription', 'user_id', 'disc', 'totalharga', 'qty', 'accountnum', 'toko','source')
                    ->where('user_id', $user_id)
                    ->get();
    
        return json_encode($dataCart);
    }

    
    public function deleteCart($id) 
    {
        DB::select("DELETE FROM cart WHERE id='".$id."' ");
        $call['code'] = 200;
        $call['message'] = "Success";
        return json_encode($call);
    }

    public function updateQtyCart()
    {
        if($_POST){
            $err = "";
            if(!isset($_POST['id'])){ $err = "Params (id) is required"; }
            if(!isset($_POST['qtyNEW'])){ $err = "Params (qtyNEW) is required"; }
            if($err == ""){
                DB::update("UPDATE cart SET qty=".$_POST['qtyNEW']." WHERE id='".$_POST['id']."'");

                $call['code'] = 200;
                $call['message'] = "Success";
                $call['post'] = $_POST;
            }else{
                $call['code'] = 400;
                $call['message'] = $err;
            }
        }else{ 
            $call['code'] = 400;
            $call['message'] = "Failed";
        }
        return json_encode($call);
    }

    public function noOrders($accountnum)
    {
        // Mendapatkan tahun berjalan
        $year = date('y');

        // Mendapatkan bulan dalam format dua digit
        $month = date('m');

        // Mendapatkan urutan order (misalnya, dari database)
        $lastOrder = Order::latest()->first(); // asumsi ada model Order
        $orderSequence = $lastOrder ? intval(substr($lastOrder->order_number, -2)) + 1 : 1;
        $orderSequence = str_pad($orderSequence, 2, '0', STR_PAD_LEFT); // Mengisi dengan nol di depan jika kurang dari 2 digit

        // Menggabungkan bagian-bagian untuk membuat nomor pesanan
        $orderNumber = 'RO' . $year . $month . 'DS' . $accountnum ;
        $latest = Order::where('no_order', 'like', '%' . $orderNumber . '%')->latest()->first();
        
        if(!$latest) {
            // If $latest is null, set $numbers to $orderNumber followed by '01'
            $numbers = $orderNumber . '01';
        } else {
            $sbstr = (is_numeric(substr($latest->no_order, -1))) ? (int) substr($latest->no_order, -1) : (int) substr($latest->no_order, -2, 1);
            if ($sbstr <= 9) {
                $increment = '0' . ($sbstr + 1);
            } else {
                $increment = $sbstr + 1;
            }
            $numbers = $orderNumber . $increment;
        }
        return $numbers;
    }

    public function inOrders()
    {
        if($_POST)
        {
            $err = "";
            $namefiledownload = $this->noOrders($_POST['accountnum']);
            if(!isset($_POST['user_id'])){ $err = "Params (user_id) is required";}
            if(!isset($_POST['totalharga'])){ $err = "Params (totalharga) is required";}
            if(!isset($_POST['accountnum'])){ $err = "Params (accountnum) is required";}
            if(!isset($_POST['namaToko'])) { $err = "Params (namaToko) is required";}
            if(!isset($_POST['item_string'])){ $err = "Params (item_string) is required"; }
            if($err == "")
            {
                DB::insert("insert into orders (no_order, accountnum, toko, user_id, totalharga ) values ('".$namefiledownload."', '".$_POST['accountnum']."', '".$_POST['namaToko']."', '".$_POST['user_id']."', ".$_POST['totalharga']." ) ");

                $exp = explode("~", $_POST['item_string']);
                foreach($exp as $exp2){
                    $a = explode("^", $exp2);//Format: userid^itemid^namelevel5^name_discription^salesprice_incl^disc^qty^totalharg^accountnum^namaToko^no_order^Source
                    DB::insert("insert into order_list (user_id, item_id, namelevel5, name_discription, salesprice_incl, disc, qty, total_harga,accountnum, namaToko, no_order, source) values('".$a[0]."', '".$a[1]."', '".$a[2]."','".$a[3]."', '".$a[4]."', ".$a[5].",".$a[6].",".$a[7].",'".$a[8]."','".$a[9]."','".$namefiledownload."','".$a[10]."')");
                }

                DB::select("DELETE FROM cart WHERE user_id='".$_POST['user_id']."' ");

                $call['code'] = 200;
                $call['message'] = "Success";
                $call['post'] = $_POST;
            }else {
                $call['code'] = 400;
                $call['message'] = $err;
            }
        }else{
            $call['code'] = 400;
            $call['message'] = "Failed";
        }
        return json_encode($call);
    }

    public function getDataOrders($user_id)
    {
        $data = DB::table('orders')->where('user_id',$user_id)->select('no_order','toko','status')->get();
        return json_encode($data);
    }

    public function getOrderList($no_order)
    {
        $data = DB::table('order_list')->where('no_order', $no_order)->select('user_id','accountnum', 'namaToko', 'no_order', 'item_id','namelevel5','name_discription','salesprice_incl', 'disc','total_harga','qty')->get();

        return json_encode($data);
    }

    public function getGrandTotal($no_order)
    {
        $dataT = DB::table('orders')->where('no_order', $no_order)->select('no_order', 'totalharga', 'user_id', 'toko', 'accountnum')->get();

        return json_encode($dataT);
    }
    
}
