<?php

namespace App\Http\Controllers;

use App\Models\Branches;
use App\Models\StockCategoryItems;
use App\Models\StockIn;
use App\Models\StockItems;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB as FacadesDB;

class StockItemController extends Controller
{
    public function index()
    {
        $categories = StockCategoryItems::all();
        return view('admin.stock_items',['categories'=>$categories]);
    }

    public function show()
    {
        $sno = 0;
        $query = StockItems::with('category')->orderBy('stk_id', 'DESC')->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {
                $categoryName = $rows->category->category_name ?? null;
                $sno++;
                $json[] = array(
                    $sno,
                    '<a href="#" class="sbyc" id="' . $rows->stk_category . '">' .$categoryName. '</a>',
                    $rows->stk_barcode,
                    $rows->stk_name,
                    $rows->stk_pprice,
                    $rows->stk_sprice_b1,
                    $rows->stk_sprice_b2,
                    $rows->stk_sprice_b3,
                    $rows->stk_qty,
                    $rows->stk_notify,
                    $rows->stk_notes,
                    '<a href="#" data-toggle="modal" data-target="#stk-item-edit-modal" class="mr-3" id="' . $rows->stk_id . '" title="Edit"><i class="fas fa-edit text-warning"></i></a>' .
                    '<a href="#" data-toggle="modal" data-target="#stk-less-qty-modal" class="mr-3" id="' . $rows->stk_id . '" title="Less Quantity"><i class="fa fa-arrow-up text-primary"></i></a>'
                );
            }
            $response = array();
            $response['success'] = true;
            $response['aaData'] = $json;
            echo json_encode($response);
        } else {
            $response = array();
            $response['sEcho'] = 0;
            $response['iTotalRecords'] = 0;
            $response['iTotalDisplayRecords'] = 0;
            $response['aaData'] = [];
            echo json_encode($response);
        }
    }
    public function generate_barcode()
    {
        $barcode = rand(1, 9);
        for ($i = 0; $i < 7; $i++) {
            $barcode .= rand(0, 9);
        }
        $bquery = StockItems::where('stk_barcode', $barcode)->first();
        if ($bquery) {
            return $this->generate_barcode();
        } else {
            echo json_encode([$barcode]);
        }
    }
    public function add(Request $request)
    {
        $msg = null;
        $stk_category     = $request->stk_category;
        $stk_barcode      = $request->stk_barcode;
        $stk_name         = $request->stk_name;
        $stk_pprice        = $request->stk_pprice;
        $stk_sprice_b1     = $request->stk_sprice_b1;
        $stk_sprice_b2     = $request->stk_sprice_b2;
        $stk_sprice_b3     = $request->stk_sprice_b3;
        $stk_qty          = $request->stk_qty;
        $stk_notify     = $request->stk_notify;
        $stk_notes         = $request->stk_notes;
        $query = StockItems::where('stk_barcode', $stk_barcode)->first();
        if ($query) {
            $msg = 2;
            echo json_encode([$msg]);
            exit;
        }
        
        $ins_array = array(
            'stk_category' => $stk_category,
            'stk_barcode' => $stk_barcode,
            'stk_name' => $stk_name,
            'stk_pprice' => $stk_pprice,
            'stk_sprice_b1' => $stk_sprice_b1,
            'stk_sprice_b2' => $stk_sprice_b2,
            'stk_sprice_b3' => $stk_sprice_b3,
            'stk_qty' => $stk_qty,
            'stk_notify' => $stk_notify,
            'stk_notes' => $stk_notes,
            'in_user' => null,
            'dated' => now()
        );
        $ins_query = StockItems::create($ins_array);
        if ($ins_query) {
            $msg = 1;
        } else {
            $msg = 0;
        }
        echo json_encode([$msg]);
    }
    public function edit(Request $request)
    {
        $stk_id = $request->stk_id;
        $query = StockItems::where('stk_id', $stk_id)->first();
        if ($query) {
            $rows = $query;
            $stk_category = $rows->stk_category;
            $stk_barcode = $rows->stk_barcode;
            $stk_name = $rows->stk_name;
            $stk_pprice = $rows->stk_pprice;
            $stk_pdate = $rows->stk_pdate;
            $stk_sprice_b1 = $rows->stk_sprice_b1;
            $stk_sprice_b2 = $rows->stk_sprice_b2;
            $stk_sprice_b3 = $rows->stk_sprice_b3;
            $stk_qty = $rows->stk_qty;
            $stk_notify = $rows->stk_notify;
            $stk_notes = $rows->stk_notes;
            $stk_provider = $rows->stk_provider;
            echo json_encode([
                'stk_category' => $stk_category,
                'stk_barcode' => $stk_barcode,
                'stk_name' => $stk_name,
                'stk_pprice' => $stk_pprice,
                'stk_sprice_b1' => $stk_sprice_b1,
                'stk_sprice_b2' => $stk_sprice_b2,
                'stk_sprice_b3' => $stk_sprice_b3,
                'stk_qty' => $stk_qty,
                'stk_notify' => $stk_notify,
                'stk_notes' => $stk_notes,
               
            ]);
        }
    }
    public function update(Request $request)
    {
        $msg = null;
        $stk_id         = $request->stk_id;
        $stk_category     = $request->stk_category;
        $stk_barcode      = $request->stk_barcode;
        $stk_name         = $request->stk_name;
        $stk_pprice        = $request->stk_pprice;
        $stk_sprice_b1     = $request->stk_sprice_b1;
        $stk_sprice_b2     = $request->stk_sprice_b2;
        $stk_sprice_b3     = $request->stk_sprice_b3;
        $stk_qty          = $request->stk_qty;
        $stk_notify     = $request->stk_notify;
        $stk_notes         = $request->stk_notes;
        $query = StockItems::where('stk_id', $stk_id)
            ->where('stk_category', $stk_category)
            ->where('stk_barcode', $stk_barcode)
            ->where('stk_name', $stk_name)
            ->where('stk_pprice', $stk_pprice)
            ->where('stk_sprice_b1', $stk_sprice_b1)
            ->where('stk_sprice_b2', $stk_sprice_b2)
            ->where('stk_sprice_b3', $stk_sprice_b3)
            ->where('stk_qty', $stk_qty)
            ->where('stk_notify', $stk_notify)
            ->where('stk_notes', $stk_notes)
            ->first();
        if ($query) {
            $msg = 2;
            echo json_encode([$msg]);
        } else {
            $query = StockItems::where('stk_id', '!=', $stk_id)
                ->where('stk_barcode', $stk_barcode)
                ->first();
            if ($query) {
                $msg = 3;
                echo json_encode([$msg]);
                exit;
            }
            $query = StockItems::where('stk_id', '!=', $stk_id)
                ->where('stk_name', $stk_name)
                ->first();
            if ($query) {
                $msg = 4;
                echo json_encode([$msg]);
                exit;
            }
            $up_array = [
                'stk_category' => $stk_category,
                'stk_barcode' => $stk_barcode,
                'stk_name' => $stk_name,
                'stk_pprice' => $stk_pprice,
                'stk_sprice_b1' => $stk_sprice_b1,
                'stk_sprice_b2' => $stk_sprice_b2,
                'stk_sprice_b3' => $stk_sprice_b3,
                'stk_qty' => $stk_qty,
                'stk_notify' => $stk_notify,
                'stk_notes' => $stk_notes,
                'in_user' => null,
                'dated' => now()
            ];
            $old_stk_barcode = StockItems::where('stk_id', $stk_id)->value('stk_barcode') ?? 0;
            $up_query = StockItems::where('stk_id', $stk_id)->update($up_array);
            if ($up_query) {
                $bquery = Branches::all();
                if ($bquery->count() > 0) {
                    foreach ($bquery as $brows) {
                        $branch_id = $brows->branch_id;
                        $table = 'stock_' . $branch_id;
                        $stk_avl = FacadesDB::table($table)->where('stk_barcode', $old_stk_barcode)->value('stk_id') ?? 0;
                        if ($stk_avl != 0) {
                            $up_array = ['stk_barcode' => $stk_barcode, 'stk_name' => $stk_name, 'stk_sprice_b' . $branch_id => ${'stk_sprice_b' . $branch_id}];
                            $up_query = $table::where('stk_barcode', $old_stk_barcode)->update($up_array);
                        }
                    }
                }
                $msg = 1;
            } else {
                $msg = 0;
            }
            echo json_encode([$msg]);
        }
    }
    public function delete($stk_id)
    {
        $delete_query = StockItems::where('stk_id', $stk_id)->delete();
        $msg = 0;
        if ($delete_query) {
           $msg=1;
        } 
        echo $msg;
    }
    public function addQty(Request $request)
    {
        $msg = null;
        $stk_id      = $request->stk_id;
        $stk_qty     = $request->stk_qty;
        $stk_date    = $request->stk_date;
        $stk_price   = $request->stk_price;
        $stk_notes   = $request->stk_notes;
        $q = StockItems::where('stk_id', $stk_id)->first();
        if ($q) {
            $r = $q;
            $stk_barcode = $r->stk_barcode;
            $old_qty = $r->stk_qty;
            $new_qty = ($old_qty + $stk_qty);
            $up_array = ['stk_qty' => $new_qty, 'stk_pprice' => $stk_price, 'dated' => now()];
            $up_query = StockItems::where('stk_id', $stk_id)->update($up_array);
            if ($up_query) {
                $ins_array = ['stk_item' => $stk_barcode, 'stk_quantity' => $stk_qty, 'stk_date' => $stk_date, 'stk_price' => $stk_price, 'stk_total' => ($stk_qty * $stk_price), 'stk_notes' => $stk_notes, 'dated' => now()];
                $ins_query = StockItems::create($ins_array);
                if ($ins_query == 1) {
                    $msg = 1;
                } else {
                    $msg = 0;
                }
            }
        } else {
            $msg = 0;
        }
        echo json_encode([$msg]);
    }

    public function lessQty(Request $request)
    {
        $msg = null;
        $stk_id      = $request->stk_id;
        $stk_qty     = $request->stk_qty;
        $reason      = $request->reason;
        $q = StockItems::where('stk_id', $stk_id)->first();
        if ($q) {
            $r = $q;
            $stk_notify = $r->stk_notify;
            $stk_name = $r->stk_name;
            $stk_barcode = $r->stk_barcode;
            $old_qty = $r->stk_qty;
            if ($stk_qty > $old_qty) {
                $msg = 3;
            } else {
                $new_qty = ($old_qty - $stk_qty);
                $up_array = [
                    'stk_qty' => $new_qty,
                    'dated' => now()
                ];
                $up_query = StockItems::where('stk_id', $stk_id)->update($up_array);
                if ($up_query) {
                    $ins_array = [
                        'stk_item' => $stk_barcode,
                        'stk_quantity' => $stk_qty,
                        'reason' => $reason,
                        'dated' => now()
                    ];
                    $ins_query = StockItems::create($ins_array);
                    if ($ins_query) {
                        $msg = 1;
                        $ins_array = [
                            'stk_item' => $stk_barcode,
                            'stk_quantity' => $stk_qty,
                            'reason' => $reason,
                            'dated' => now()
                        ];
                        $ins_query = StockItems::create($ins_array);

                        if ($new_qty <= $stk_notify) {
                            $ins_array = [
                                'notify_type' => 'STOCK ITEMS',
                                'notify_text' => $stk_name . ' is running out',
                                'dated' => now()
                            ];
                            $ins_query = StockItems::create($ins_array);
                        }
                    } else {
                        $msg = 0;
                    }
                }
            }
        } else {
            $msg = 0;
        }
        echo json_encode([$msg]);
    }

    public function transfer_qty(Request $request)
    {
        $stk_id      = $request->stk_id;
        $qty         = 0;
        $stk         = 'Not Found';
        $q = StockItems::where('stk_id', $stk_id)->first();
        if ($q) {
            $r   = $q;
            $stk = $r->stk_barcode . '-' . $r->stk_name;
            $qty = $r->stk_qty;
        }
        $options = null;
        $query = StockItems::all();
        if ($query->count() > 0) {
            $options .= '<option value="" selected>Select</option>';
            foreach ($query->result() as $rows) {
                $options .= '<option value="' . $rows->stk_id . '">' . $rows->stk_barcode . '-' . $rows->stk_name . '</option>';
            }
        }
        echo json_encode([
            'stk' => $stk,
            'qty' => $qty,
            'options' => $options
        ]);
    }

    public function getTransferInfo(Request $request)
    {
        $stk_id = $request->stk_trf_to_id;
        $stk_barcode = explode('+', $stk_id);
        $stk_barcode = end($stk_barcode);
        $qty = 0;
        $q = StockItems::where('stk_barcode', $stk_barcode)->first();
        if ($q) {
            $r = $q;
            $qty = $r->stk_qty;
        }
        echo json_encode([$qty]);
    }
    public function processTransfer(Request $request)
    {
        $msgb = null;
        $msgc = null;
        $stk_trf_frm_id = $request->stk_trf_frm_id;
        $stk_trf_to_id = $request->stk_trf_to_id;
        $stk_trf_to_id = explode('+', $stk_trf_to_id);
        $stk_trf_to_id = end($stk_trf_to_id);
        $stk_base_qty2 = $request->stk_base_qty2;
        $stk_converted_qty2 = $request->stk_converted_qty2;
        $reason = $request->reason;


        $q1 = StockItems::where('stk_id', $stk_trf_frm_id)->first();


        $q2 = StockItems::where('stk_barcode', $stk_trf_to_id)->first();


        if ($q1 && $q2) {
            $r1 = $q1;
            $stk_bname = $r1->stk_name;
            $stk_bbarcode = $r1->stk_barcode;
            $old_bqty = $r1->stk_qty;

            $r2 = $q2;
            $stk_cname = $r2->stk_name;
            $stk_cbarcode = $r2->stk_barcode;
            $old_cqty = $r2->stk_qty;

            if ($stk_base_qty2 > $old_bqty) {
                $msg = 3;
            } else {
                $new_bqty = ($old_bqty - $stk_base_qty2);
                $up_array = [
                    'stk_qty' => $new_bqty,
                    'dated' => now()
                ];
                $up_query = StockItems::where('stk_id', $stk_trf_frm_id)->update($up_array);
                if ($up_query) {
                    $ins_array = [
                        'stk_item' => $stk_bbarcode,
                        'stk_quantity' => $stk_base_qty2,
                        'reason' => $reason,
                        'dated' => now()
                    ];
                    $ins_query = StockItems::create($ins_array);
                    if ($ins_query) {
                        $msgb = 1;
                        $new_cqty = ($old_cqty + $stk_converted_qty2);
                        $up_array = [
                            'stk_qty' => $new_cqty,
                            'dated' => now()
                        ];
                        $up_query = StockItems::where('stk_barcode', $stk_trf_to_id)->update($up_array);
                        if ($up_query) {
                            $ins_array = [
                                'stk_item' => $stk_cbarcode,
                                'stk_quantity' => $stk_converted_qty2,
                                'reason' => $reason,
                                'dated' => now()
                            ];
                            $ins_query = StockItems::create($ins_array);
                            if ($ins_query) {
                                $msgc = 1;
                            } else {
                                $msgc = 0;
                            }
                        }
                        //     if ($new_cqty <= $stk_notify) {
                        //         $ins_array = array('notify_type' => 'STOCK ITEMS', 'notify_text' => $stk_bname . ' is running out', 'dated' => timestamp);
                        //         $this->db->insert('notifications', $ins_array);
                        //     }
                        // } else {
                        //     $msgb = 0;
                    }
                }
            }
        } else {
            $msg = 0;
        }
        if ($msgb != 0 && $msgc != 0) {
            $msg = 1;
        } else {
            $msg = 0;
        }
        echo json_encode([$msg]);
    }

    // ADDITION
    public function addition()
    {
        return view('admin.stock_addition');
    }


    public function process_addition_items(Request $request)
    {
        $item_name   = json_decode($request->item_name);
        $item_price  = json_decode($request->item_price);
        $item_qty    = json_decode($request->item_qty);
        $item_total  = json_decode($request->item_total);
        $item_date   = json_decode($request->item_date);
        $item_notes  = json_decode($request->item_notes);
        $ins_query   = 0;
        for ($i = 0; $i < count($item_name); $i++) {
            $exp = explode('+', $item_name[$i]);
            $stk_barcode = end($exp);
            $old_qty = StockItems::where('stk_barcode', $stk_barcode)->value('stk_qty') ?? 0;
            $new_qty = ($old_qty + $item_qty[$i]);
            $up_array = [
                'stk_qty' => $new_qty,
                'stk_pprice' => $item_price[$i],
            ];
            $up_query = StockItems::where('stk_barcode', $stk_barcode)->update($up_array);
            if ($up_query) {
                $ins_array = [
                    'stk_item' => $stk_barcode,
                    'stk_quantity' => $item_qty[$i],
                    'stk_date' => $item_date[$i],
                    'stk_price' => $item_price[$i],
                    'stk_total' => ($item_qty[$i] * $item_price[$i]),
                    'stk_notes' => $item_notes[$i],
                ];
                $ins_query += StockIn::create($ins_array)->count();
            }
        }
        if ($ins_query > 0) {
            $msg = 1;
        } else {
            $msg = 0;
        }
        echo json_encode([$msg]);
    }
}
