<?php

namespace App\Http\Controllers\Administrator;

use App\Fun\Fun;
use App\Model\stock_inventory\ItemRequestModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\DataTables;

class RequestStockController extends Controller
{

    public function index(Request $request)
    {
        if ($request->ajax()) {
            Fun::lang();
            $search         = $request->input('search.value');
            $request_by     = $request->request_by;
            $data           = ItemRequestModel::where(function ($query) use ($request_by) {
                if ($request_by) {
                    $query->Where('nso007_item_request.request_by', $request_by);
                }
            })
            ->where(function ($query) use ($search) {
                $query->orWhere('nso007_item_request.invoice_number', 'LIKE', '%' . $search . '%');
            })
            ->orderBy('nso007_item_request.id', 'DESC');
            if ($request->isMethod('get'))
            {
                return DataTables::of($data)
                    ->addColumn('request_by', function ($item) {
                        return findUser($item->request_by)->name;
                    })
                    ->addColumn('date', function ($item) {
                        return date('d-m-Y',strtotime($item->date));
                    })
                    ->addColumn('status', function ($item) {
                        return checkRequestStatus($item->status);
                    })
                    ->addColumn('action', function ($item) {
                        return '<a data-id="' . $item->id . '" data-href="' . route("request-stock-item.show", $item->id) . '" title="'.__('administrator.show').'" class="button_warning show_request">' . __('administrator.show') . '</a>';
                    })
                    ->addIndexColumn()
                    ->rawColumns([ 'action' => 'action',  'status' => 'status'])
                    ->make(true);
            }
        }
        return view('administrator.request-stock.index');
    }

    public function show($id)
    {
        $item           = ItemRequestModel::find($id);
        $item_detail    = ItemRequestDetailModel::where('production_id',$id)->get();
        $view           =  view('administrator.request-stock.show',compact('item','item_detail'))->render();
        return response()->json(['html' => $view, 'status' => $item->statubs, 'done_status' => $item->done_status]);
    }

    public function request_stock_item_update(Request $request)
    {

        $this->validate($request, [
            'id'        => 'required',
            'status'    => 'required',
        ]);
        $check_row      = 0;
        $count_message  = 0;
        $item           = ItemRequestModel::find($request->id);
        $item_detail    = ItemRequestDetailModel::where('production_id', $request->id)->get();
        $count_row      = $item_detail->count();
        $status         = $request->status;

        $message        = '<ul class="text-left">';
        $wh_id          = getMainWarehouse()->id;

        if ($status == 1)
        {
            foreach ($item_detail as $key => $row)
            {
                // check if all product has enough stock
                $stock = StockModel::where(['warehouse_id' => $wh_id, 'product_id' => $row->product_id])->first();

                $cut_qty = generateSaleCutQty($row, 1);

                if ($stock->stock_qty >= $cut_qty)
                {
                    $check_row++;
                } else {
                    $count_message++;
                    $message .= '<li><span class="fa fa-circle text-danger"></span> ' . getProductById($row->material_id)->product_name . ' is not enough quantity.</li>';
                }
            }

            if ($count_row == $check_row)
            {
                foreach ($item_detail as $key => $row)
                {
                    $stock = StockModel::where(['warehouse_id' => $wh_id, 'product_id' => $row->product_id])->first();
                    if ($stock->stock_qty >= $cut_qty)
                    {
                        $stock->stock_qty -= $cut_qty;
                        $stock->save();
                    }
                }
            }
        }

        $item->status       = $status;
        $item->approve_by   = Auth::user()->id;
        $item->approve_date = date('Y-m-d H:i:s');
        $item->warehouse_id = $wh_id;
        $item->status_note  = $request->note;
        $item->update();

        $message .= '</ul>';
        if ($count_message > 0)
        {
            return response()->json(['status' => 'fail', 'count' => $count_message, 'message' => $message]);

        } else {
            session()->put('success', 'Updated successful');
            return response()->json(['status' => 'success']);
        }
    }


}
