<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Common;
use App\SeasonMaster;
use App\SupplierProductSeason;
use Auth;

class SeasonMasterController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
    	$seasons = SeasonMaster::all();
        $months = ['1' => 'January','2' => 'February','3' => 'March','4' => 'April','5' => 'May','6' => 'June','7' => 'July','8' => 'August','9' => 'September','10' => 'October','11' => 'November','12' => 'December']; 
        return view('season/masters', compact('seasons','months'));
    }

    public function create(Request $request)
    {
        if($request->get('edit') == 0) {
            SeasonMaster::create([
                'season' => strtoupper($request->get('season')),
                'start_month' => $request->get('from_month'),
                'end_month' => $request->get('to_month'),
                'entered_by' => Auth::user()->id
            ]);
        } else {
            SeasonMaster::where('id','=',$request->get('edit'))
                ->update([
                    'season' => strtoupper($request->get('season')),
                    'start_month' => $request->get('from_month'),
                    'end_month' => $request->get('to_month'),
                    'entered_by' => Auth::user()->id
                ]);
        }

    	return redirect()->route('season.master');
    }

    public function edit(Request $request)
    {
        $season = SeasonMaster::find($request->get('option'));
        return $season;
    }

    public function supplierSeason(Request $request)
    {
        $request->get('seasons');
        $request->get('product');
        $request->get('supplier');
        $pre_cntr = SupplierProductSeason::where('supplier_id','=',$request->get('supplier'))
                                ->where('product_id','=',$request->get('product'))->count();
        SupplierProductSeason::where('supplier_id','=',$request->get('supplier'))->where('product_id','=',$request->get('product'))->delete();
        $cntr = 0;
        foreach ($request->get('seasons') as $season) {
            $cntr++;
            SupplierProductSeason::create([
                'supplier_id' => $request->get('supplier'),
                'season_master_id' => $season,
                'product_id' => $request->get('product')
            ]);
        }

        return ($pre_cntr > $cntr)? 0 : 1;

    }



}