<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Classes\MainCore;
use App\Http\Controllers\Controller;
use App\Models\branch_user;
use App\Models\Branches;
use App\Models\ItemStock;
use App\Models\ItemMaster;
use App\Models\Notifications;
use App\Models\Stock;
use App\Models\Packages;
use App\Models\PackageDetails;
use App\Models\StockDoc;
use App\Models\StockDocDetails;
use App\Models\TransferStock;
use Illuminate\Http\Request;

use App\User;
use Illuminate\Support\Facades\Auth;

class StockController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function branch_id(){
        if (Auth::user()->is_admin == 1){
            return 1;
        }else{
            return 2;
        }
    }
    public function stock_id(){
        $id=StockDoc::select('stock_doc_id')->where('branch_number',$this->branch_id())->max('stock_doc_id');
        $id++;
        return $id;
    }
    public function index()
    {
//        $getmainbranchid = Branches::where('is_center', '1')->select('id')->get();
//        $getbranchwithstock = branch_user::where('user_id', Auth::user()->id)->with('stock')->get();
//        $allstockforallbranches = MainCore::readAll('', '', '\App\Models\Stock', ['products', 'branch']);
        $getstockformainbranch = ItemStock::with('branch')->where('branch_number',$this->branch_id())->get();
        $branches = Branches::all();
        return view('package', compact('getstockformainbranch','branches'));
    }
    public function importDocs(){

        $docs=StockDoc::with('details','branchfrom')->where('branch_number',$this->branch_id())->where('stock_branch_to',$this->branch_id())->get();
        $pending=StockDoc::with('details','branchfrom')->where('ref_stock_doc',NULL)->where('stock_branch_to',$this->branch_id())->get();
//        dd($docs);
        foreach ($pending as $key=>$value){
            $exist= StockDoc::where('ref_stock_doc',$value->stock_doc_id)->first();
            if ($exist){
                unset($pending[$key]);
            }
        }
        return view('importDocs',compact('docs','pending'));
    }

    public function exportDocs(){
        $docs=StockDoc::with('details','branchto')->where('branch_number',$this->branch_id())->where('stock_branch_from',$this->branch_id())->get();
        return view('exportDocs',compact('docs'));
    }


    public function transfer(Request $request)
    {

//        dd(Auth::user()->getuserbranchid()[0]->Id);
        $doc= new StockDoc();
//        $doc->ref_stock_doc = ;
        $doc->stock_doc_id = $this->stock_id();
        $doc->branch_number = $request->branchFrom;
        $doc->stock_branch_from = $request->branchFrom;
        $doc->stock_branch_to = $request->branchTo;
//        $doc->stock_branch_date = _current_time();
        $doc->trans_type = 1;
        $doc->stock_doc_status = 1;
        $doc->stock_doc_createdby = Auth::user()->id;
        $doc->save();

        if ($doc){

            $not= new Notifications();
            $not->notification_text = "you have a new Document from branch number : ".$request->branchFrom;
            $not->branch_number = $request->branchTo;
            $not->type = 2;
            $not->save();

            foreach ($request->quantity as $key=>$value){
                if(!empty($value)) {
                    $item = ItemStock::where('item_stock_id', $key)->first();

                    $docDetails = new StockDocDetails();
                    $docDetails->stock_doc_id = $doc->stock_doc_id;
                    $docDetails->stock_id = $doc->id;
                    $docDetails->branch_number=$doc->branch_number;
                    $docDetails->item_code = $item->item_code;
                    $docDetails->ref_code = $item->ref_code;
                    $docDetails->item_serial = $item->item_serial;
                    $docDetails->item_quantity = $value;
                    $docDetails->item_width = $item->item_width;
                    $docDetails->item_length = $item->item_length;
                    $docDetails->save();
                }
            }


        }
        return redirect()->route('stock');
    }

    public function acceptDoc($id){
        $doc = StockDoc::with('details')->where('id',$id)->first();
        $accept = new StockDoc();
        $accept->stock_doc_id = $this->stock_id();
        $accept->ref_stock_doc = $doc->stock_doc_id;
        $accept->branch_number = $this->branch_id();
        $accept->stock_branch_from = $doc->stock_branch_from;
        $accept->stock_branch_to = $doc->stock_branch_to;
//        $accept->stock_branch_date = _current_time();
        $accept->trans_type = 2;
        $accept->stock_doc_status = 2;
        $accept->stock_doc_createdby = Auth::user()->id;
        $accept->save();

        if ($accept){
            $not= new Notifications();
            $not->notification_text = "your Document was accepted to branch number : ".$doc->stock_branch_to;
            $not->branch_number = $doc->stock_branch_from;
            $not->type = 1;
            $not->save();
            foreach ($doc->details as $item){
                $newDetails=$item->replicate();
                $newDetails->stock_doc_details_id = null;
                $newDetails->stock_id = $accept->id;
                $newDetails->save();

                $product = ItemStock::where('item_serial',strval($item->item_serial))->where('branch_number',$doc->stock_branch_from)->first();
                $product->item_quantity = $product->item_quantity-$item->item_quantity;
                $product->save();

                $new= new ItemStock();
                $new->item_code=$product->item_code;
                $new->ref_code=$product->ref_code;
                $new->item_serial=$product->item_serial;
                $new->item_quantity=$item->item_quantity;
                $new->item_width=$product->item_width;
                $new->item_length=$product->item_length;
                $new->item_class=$product->item_class;
                $new->post_date=date('Y-m-d');
                $new->stock_doc_type=$product->stock_doc_type;
                $new->stock_doc_number=$doc->stock_doc_id;
                $new->branch_number=$this->branch_id();

                $new->save();
            }
        }

        return redirect()->route('importDocs');
    }

    public function nots($id){
        $not=Notifications::where('notifications_id',$id)->first();
        $not->is_read=1;
        $not->save();
        if($not->type==2){
            return redirect()->route('importDocs');
        }elseif ($not->type==1){
            return redirect()->route('exportDocs');
        }
    }

    public function viewstock()
    {

        $getmainbranchid = Branches::where('is_center', '1')->select('id')->get();

        $getbranchwithstock = branch_user::where('user_id', Auth::user()->id)->with('stock')->get();
        $allstockforallbranches = MainCore::readAll('', '', '\App\Models\Stock', ['products', 'branch']);
        $getstockformainbranch = Stock::where('branch_id',Auth::user()->getuserbranchid()[0]->branch_id)->with('products','branch')->get();

        return view('viewstock', compact('getstockformainbranch','allstockforallbranches'));

    }

    public function requestPackage()
    {
        $user_id=Auth::user()->id;

        $allstockforallbranches = MainCore::readAll('', '', '\App\Models\Stock', ['products', 'branch']);
//        dd( $allstockforallbranches[0]->branch->id);
        return view('requestPackage', compact('allstockforallbranches','user_id'));
    }
    public function requestPackageSubmit(Request $request)
    {
//dd($request->all());
        $idstock=$request->idstock;
        $quantity=$request->quantity;
        $userrequest=$request->user_id;
        $userrequestbranch=branch_user::where('user_id', $userrequest)->first(); //frombranch
        $from=$userrequestbranch->id;
        $productids=$request->productids;
        $productsnew=array_slice( $productids, 0, count( $idstock));
        $qunew = array_slice( $quantity, 0, count( $idstock));

        $branchesid=$request->branchids;
        $branchesnew = array_slice( $branchesid, 0, count( $idstock));
        $totalquantity=array_sum($qunew);
        $newpackage= new Packages;
        $newpackage->name=time().$userrequest. 'user requestpackage';
        $newpackage->total_quantity=$totalquantity;
        $newpackage->save();


        if($newpackage)
        {
            $newpackagedetails= new PackageDetails;
             $to= Stock::select('branch_id')->where('id',$branchesnew[0])->first();
            for($i=0;$i<count($idstock);$i++)
            {

                $newpackagedetails->package_id=$newpackage->id;
                $newpackagedetails->product_id=$productsnew[$i];
                $newpackagedetails->quntity=$qunew[$i];
                $newpackagedetails->save();
            }

                $newtransferStock= new TransferStock;
                $newtransferStock->package_id= $newpackage->id;
                $newtransferStock->status= "request";
                $newtransferStock->from_branch= $from;
                $newtransferStock->to_branch= $to;
            $newtransferStock->user_id= $userrequest;
            $newtransferStock->save();
            return redirect()->route('requestPackage');




        }

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        return $request;

    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
