<?php

namespace App\Http\Controllers;

use App\DataTables\QualityCheckDataTable;
use App\Http\Requests;
use App\Http\Requests\CreateQualityCheckRequest;
use App\Http\Requests\UpdateQualityCheckRequest;
use App\Repositories\QualityCheckRepository;
use Flash;
use App\Http\Controllers\AppBaseController;
use Response;
use Illuminate\Http\Request;
use Log;

class QualityCheckController extends AppBaseController
{
    /** @var  QualityCheckRepository */
    private $qualityCheckRepository;

    public function __construct(QualityCheckRepository $qualityCheckRepo)
    {
        $this->qualityCheckRepository = $qualityCheckRepo;
    }

    /**
     * Display a listing of the QualityCheck.
     *
     * @param QualityCheckDataTable $qualityCheckDataTable
     * @return Response
     */
    public function index(QualityCheckDataTable $qualityCheckDataTable)
    {
        return $qualityCheckDataTable->render('quality_checks.index');
    }


    private function updateData($input){
        $input['net_qty'] = $this->getData($input,'qty') +$this->getData($input,'rejection_under_size_qty') + $this->getData($input,'rejection_over_size_qty') + $this->getData($input,'rejection_shape_qty');
        return $input;
    }

    private function getData($input, $name){
        if(isset($input[$name])){
            return (float)$input[$name];
        }
        return 0;
    }
    /**
     * Show the form for creating a new QualityCheck.
     *
     * @return Response
     */
    public function create()
    {
        return view('quality_checks.create');
    }

    /**
     * Store a newly created QualityCheck in storage.
     *
     * @param CreateQualityCheckRequest $request
     *
     * @return Response
     */
    public function store(CreateQualityCheckRequest $request)
    {
        $input = $request->all();

        $input = $this->updateData($input);

        $this->validateQuality($input['material_id'], $input['net_qty'], null);

        $qualityCheck = $this->qualityCheckRepository->create($input);

        if($request->expectsJson()){
            return  $this->sendResponse( new \App\Http\Resources\Production\QualityCheckResource($qualityCheck), "Quality Check created successfully");
        }else{
            Flash::success('Quality Check saved successfully.');
            return redirect(route('qualityChecks.index'));
        }
        
    }

    private function validateQuality($materialId, $qty, $check){
        $totalProductionPcs = \App\Models\BondMaterialRecipe::getTotalProductionPcs($materialId);
        $qualityCheckPcs = \App\Models\QualityCheck::getTotalProduction($materialId);
        $netPcs = $totalProductionPcs - $qualityCheckPcs;
        if($check){
            $netPcs = $netPcs + $check->net_qty;
        }
        
        //Log::info('qty '.$qty. ' totalProductionPcs '.$totalProductionPcs);
        if($qty > ($netPcs)){
            $error = \Illuminate\Validation\ValidationException::withMessages([
                'qty' => ['You cannot do quality check for more than '.$netPcs.' produced pcs ']
             ]);
             throw $error;
        }
        return false;
    }

    /**
     * Display the specified QualityCheck.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id, Request $request)
    {
        $qualityCheck = $this->qualityCheckRepository->find($id);

        if($this->checkEmpty($qualityCheck, $request)){
            return;
        }


        return view('quality_checks.show')->with('qualityCheck', $qualityCheck);
    }

    /**
     * Show the form for editing the specified QualityCheck.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id, Request $request)
    {
        $qualityCheck = $this->qualityCheckRepository->find($id);

        if($this->checkEmpty($qualityCheck, $request)){
            return;
        }


        return view('quality_checks.edit')->with('qualityCheck', $qualityCheck);
    }

    /**
     * Update the specified QualityCheck in storage.
     *
     * @param  int              $id
     * @param UpdateQualityCheckRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateQualityCheckRequest $request)
    {
        $qualityCheck = $this->qualityCheckRepository->find($id);

        $input = $request->all();
        $input = $this->updateData($input);

        $this->validateQuality($input['material_id'], $input['net_qty'], $qualityCheck);

        if($this->checkEmpty($qualityCheck, $request)){
            return;
        }


        $qualityCheck = $this->qualityCheckRepository->update($input, $id);

        if($request->expectsJson()){
            return  $this->sendResponse( new \App\Http\Resources\Production\QualityCheckResource($qualityCheck), "Quality Check updated succesfully.");
        }else{
            Flash::success('Quality Check updated successfully.');
            return redirect(route('qualityChecks.index'));
        }
    }

    /**
     * Remove the specified QualityCheck from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id, Request $request)
    {
        $qualityCheck = $this->qualityCheckRepository->find($id);

        if($this->checkEmpty($qualityCheck, $request)){
            return;
        }


        
        $this->qualityCheckRepository->delete($id);

        if($request->expectsJson()){
            return  $this->sendResponseMessage('Quality Check deleted successfully.');;
        }else{
            Flash::success('Quality Check deleted successfully.');
             return redirect(route('qualityChecks.index'));
        }
    }

    private function  checkEmpty($bondMaterialRecipe , $request){
        if (empty($bondMaterialRecipe)){
            if($request->expectsJson()){
                return $this->sendError('Quality check not found', 400);
            }else{
                Flash::error('Quality Check not found');
                return redirect(route('qualityChecks.index'));
            }
        }
    }
}
