<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Hash;
use Request as Req;
use Auth;

class FarmerController extends Controller
{
	public function __construct()
    {
        parent::__construct($this->masterModel);

        $email=Req::header('email');
        $pass=Req::header('password');
        
        if(!Auth::attempt(['email' => $email, 'password' => $pass]))
        {
            echo response()->json(['error'=>'Unauthorised'], 401);
            die();
        }

    }
    public function getMarqua(Request $request){
        $data=$this->masterModel->getAllData('marqua',['crop'=>$request['crop']]);
        if($data){
            return $this->masterModel->successResponse($data);
        } else{
            return $this->masterModel->failureResponse('Marqua Not Available');
        }
    }

    public function addFarmer(Request $request)
    {
    	// $request = json_decode(file_get_contents('php://input'),true);
        // dd($request);
        $validator = \Validator::make($request->all(),[
                        'name'=>'required',
                        'mobile'=>'required|min:10|unique:farmers,mobile',    
                    ]);

        if ($validator->fails()) {
            return $this->masterModel->failureResponse($validator->messages());
        }	
    	// dd($request['crop_transactions']);     
        $data = [
            'tc_id'=>$request['traderCId'] ?? '',
            't_id'=>$request['traderId'] ?? '' ,
            'name'=>$request['name']?? '',
            'email'=>$request['email']?? '',
            'mobile'=>$request['mobile']?? '',
            'status'=>1,
            'created'=>date('Y-m-d H:i:s')
        ];

        $exist = $this->masterModel->checkDataExist('farmers',['tc_id'=>$request['traderCId'],'mobile'=>$request['mobile']]);
        if(!$exist)
        {
           $farmerId = $this->masterModel->addDataGetID('farmers',$data);

           $purchase = [
                'patti_no'=>$this->getPattiNumber(),
                'tc_id'=>$request['traderCId'],
                'trader'=>$request['traderId'],
                'farmer'=>$farmerId,
                'transporter_name'=>$request['transporter_name'] ?? '',
                'truck_no'=>$request['truck_number'] ?? '',
                'freight_charge'=>$request['freight_charge'] ?? '',
                'status'=>1,
                'created'=>date('Y-m-d H:i:s')
            ];

           $purchaseId = $this->masterModel->addDataGetID('purchase',$purchase);

           foreach ($request['crop_transactions'] as $key => $value) {
           	   $value['purchaseId'] = $purchaseId;
               $value['ctType'] = 1;
	           $this->addCropTransaction($value);
           }

           $request['purchaseId'] = $purchaseId;
           $request['farmerId'] = $farmerId;
           $this->addTransaction($request);
           return $this->masterModel->successResponse('Farmer added successfully');
        }
        else
        {
        	return $this->masterModel->failureResponse('Farmer already exist!');	
        }
    }

    public function addCropTransaction($request)
    {
    	$crop_transaction = [
                'type'=>$request['ctType'],
                'pr_id'=>isset($request['purchaseId']) ? $request['purchaseId'] : 0,
                'sell_id'=>isset($request['sell']) ? $request['sell'] : 0,
                'crop'=>$request['crop'] ?? '',
                'marqua'=>$request['quality'] ?? '',
                'quantity'=>$request['quantity'] ?? '',
                'bangdi'=>$request['bangadi'] ?? '',
                'weight'=>$request['weight'] ?? '',
                'cost'=>$request['cost'] ?? '',
                'status'=>1,
                'created'=>date('Y-m-d H:i:s')
           ];
           
       $this->masterModel->addData('crop_transactions',$crop_transaction);
    }

    public function addTransaction($request)
    {
    	$transaction = [
    		'tc_id'=>$request['traderCId'],
    		'trader'=>$request['traderId'],
    		'farmer'=>$request['farmerId'],
    		'buyer'=>$request['buyer'],
    		'p_id'=>isset($request['purchaseId']) ? $request['purchaseId'] : 0,
    		's_id'=>isset($request['sell']) ? $request['sell'] : 0,
    		'amount'=>$request['amount'] ?? '',
    		'pay_type'=>$request['payment_type'] ?? '',
    		'bank_name'=>$request['bank_name'] ?? '',
    		'cheque_no'=>$request['cheque_number'] ?? '',
    		'remark'=>$request['remark'] ?? '',
    		'status'=>1,
            'created'=>date('Y-m-d H:i:s')
    	];

    	$this->masterModel->addData('transactions',$transaction);
    }

    public function getPattiNumber()
    {
        
            // Get the last created order
            $lastOrder = DB::table('purchase')->whereRaw('year(created)='.date("Y"))->orderBy('p_id', 'desc')->first();
            // dd($lastOrder);
            if ( ! $lastOrder )
                // We get here if there is no order at all
                // If there is no number set it to 0, which will be 1 at the end.

                $number = date ('Y').(100000);
            else 
                $number = $lastOrder->patti_no;
                // $number = substr($lastOrder->patti_no, 5);

            // If we have ORD000001 in the database then we only want the number
            // So the substr returns this 000001

            // Add the string in front and higher up the number.
            // the %05d part makes sure that there are always 6 numbers in the string.
            // so it adds the missing zero's when needed.
         // dd($number);
            return ($number + 1);
        
    }

    public function getSuggestion(Request $request)
    {
        // dd($request->all());
        if($request->input('table')=='crops' )
        {
            $data = DB::table($request->input('table'))->where($request->input('field'), 'like', '%' . $request->input('value') . '%')->get();
        }else if($request->input('table')=='marqua'){
            $data = DB::table($request->input('table'))->where('crop',$request->input('crop'))->where($request->input('field'), 'like', '%' . $request->input('value') . '%')->get();

        }else
        {
            $data = DB::table($request->input('table'))->where('tc_id',$request->input('traderCId'))->where($request->input('field'), 'like', '%' . $request->input('value') . '%')->get();
        }
        return $this->masterModel->successResponse($data);
    }

    public function getPurchase(Request $request)
    {
        $tcId=$request->input('traderCId');
        $tId=$request->input('traderId');
        $s=[];
        $q=DB::table('purchase');
        if($request->input('flag')==2)
        {
            $q->where('purchase.trader',$tId);
        }
            $q->where('purchase.tc_id',$tcId);
            $q->join('farmers','farmers.f_id','=','purchase.farmer');
        $data=$q->get();
        foreach ($data as $key => $value) {
            $s[$key]['purchase']=$value;
            $s[$key]['crops']=$this->masterModel->customequery('select crop_transactions.*,crops.crop as crop_name,marqua.quality as crop_quality from crop_transactions left join crops on crop_transactions.crop=crops.crp_id left join marqua on marqua.mq_id=crop_transactions.marqua where pr_id='.$value->p_id);
        }
        // dd($data,$s);
        if(count($s))
        {
            return $this->masterModel->successResponse($s); 
        }else
        {
            return $this->masterModel->failureResponse('No purchase data found!');
        }
    }


}