<?php
namespace App\Http\Controllers\API\Dashboard;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Response;
use App\Http\Resources\User\UserResource;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Log;
use Carbon\Carbon;
use App\Repositories\QualityCheckRepository;
use Illuminate\Validation\Rule;
use App\Utils\Util;
/**
 * Class DemoController
 * @package App\Http\Controllers\API
 */

class ProductionDashboardController extends AppBaseController
{
    const V_COLOR = '#3D3D3D';
    const S_COLOR = '#7D7D7D';

    public function dashboard1(Request $request){
        $currentMonthItem = new \stdClass();

        $todaysSection = $this->getTodaysProduction(date('Y-m-d'),'');
        $monthSection = $this->getTodaysProduction('', date('m'));
        $netSummary = $this->getNetProductionSummary(date('m'));
        //$avgSection = $this->getTodaysProduction('', date('m'), true);    
        $array =null;
        if($netSummary !=null){
            $array = array($todaysSection, $monthSection, $netSummary);
        }else{
            $array = array($todaysSection, $monthSection);
        }
        
        //dd(collect($array));
        return \App\Http\Resources\Dasboard\DashboardSectionResource::collection(collect($array));
    }



    private function getNetProductionSummary($month){
        $tmp = DB::select('select sum(mould) as mould,sum(remaining_piece) as remaining_piece,sum(duration) as duration,end_month,
        sum(weight) as weight, sum(electricity_out_duration) as electricity_out_duration, 
        sum(other_prod_blocker_duration) as other_prod_blocker_duration, 
        max(bond_process_id) as bond_process_id,unit,max(piece_per_mould) as piece_per_mould,
        ((sum(mould)*max(piece_per_mould))+sum(remaining_piece)) as total_piece     
        from bond_production_view where end_month= ? ', [ $month]);
        $data = !empty($tmp)?$tmp[0]:null;
        $tmp  = DB::select('select sum(qty) as qty, sum(rejection_under_size_qty) as rejection_under_size_qty,unit,sum(rejection_over_size_qty) as rejection_over_size_qty, sum(rejection_shape_qty) as rejection_shape_qty, sum(net_qty) as net_qty ,created_date,created_month  from qc_view where created_month= ?', [ $month]); 
        $qc = !empty($tmp)?$tmp[0]:null;
        $tmp  = DB::select('select sum(qty) as qty,created_date, created_month,unit  from packing_view where created_month= ? ', [ $month]);
        $pk = !empty($tmp)?$tmp[0]:null;

        if(empty($data)){
            return null;
        }


        $dItemArray = array();

        $section = new \stdClass();  
        $mt = Carbon::createFromFormat('m' , ($month));
        $section->name= 'All Product Production Summary of '.$mt->format('F');
        $section->desc = null;
        $section->type='card';

        $dItem = new \stdClass();
        $dItem->heading = 'Production Summary';
        $dItem->items= array();

        $item = new \stdClass();
        $item->name = 'Total Production Time';
        $item->value= Util::sToTime(($data->duration/1000));
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));  

        $item = new \stdClass();
        $item->name = 'Net Electricity Out Time';
        $item->value= Util::sToTime(($data->electricity_out_duration*60));
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));


        $item = new \stdClass();
        $item->name = 'Other Production Blocker Duration';
        $item->value= Util::sToTime(($data->other_prod_blocker_duration*60));
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));

        $item = new \stdClass();
        $item->name = 'Net Powder Weight';
        $item->value= Util::f(($data->weight/1000)).' Kg';
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));

        $item = new \stdClass();
        $item->name = 'Net Mould';
        $item->value= Util::f(($data->mould));
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));


        

        $item = new \stdClass();
        $item->name = 'Net Produced Pcs';
        $item->value= Util::f(($data->total_piece)).' '.$data->unit;
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));  


        $item = new \stdClass();
        $item->name = 'Net QC Pcs';
        $item->value= Util::f(($qc->qty)).' '.$qc->unit;
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));  

        $item = new \stdClass();
        $item->name = 'Net Packed PCS';
        $item->value= Util::f(($pk->qty)).' '.$pk->unit;
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));  

        $netRej = $qc->rejection_under_size_qty+$qc->rejection_over_size_qty+$qc->rejection_shape_qty;
        $item = new \stdClass();
        $item->name = 'Total Rejected PCS';
        $item->value= Util::f(($netRej)).' '.$pk->unit;
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));  

        $recjPercentage= ($netRej/$data->total_piece)*100;

        $item = new \stdClass();
        $item->name = 'Rejected (%)';
        $item->value= Util::f(($recjPercentage)).' %';
        $item->s_text = '';
        $item->value_color = self::V_COLOR;
        $item->scolor = self::S_COLOR;
        array_push($dItem->items, ($item));  

        $dItem->items = collect($dItem->items);

        array_push($dItemArray, $dItem);

        $section->items = collect($dItemArray);
        return $section;
    }
    

    private function getTodaysProduction($todayDate, $month, $avg = false){
        $productTypes = DB::select('select id,name from bond_product_types');

        $dItemArray = array();

        $section = new \stdClass();    
        $heading = '';
        if(!empty($todayDate)){
            $dt = Carbon::createFromFormat('Y-m-d' , ($todayDate));
            $section->name= 'Production Summary of '.$dt->format('d F');
            $section->desc = null;
            $section->type='card';
            $heading = $heading;
        }else if(!empty($month)){
            $mt = Carbon::createFromFormat('m' , ($month));
            $section->name= 'Production Summary of '.$mt->format('F');
            $section->desc = null;
            $section->type='card';
            $heading = '';
        }
        $tp =0;
        $elOut =0;
        $otherBlocker=0; 
        $tw=0;
        foreach($productTypes as $type){
            
            $data=null;
            $qc=null;
            $pk=null;
            if(!empty($todayDate)){
                $tmp= DB::select('select sum(mould) as mould, sum(remaining_piece) as remaining_piece,sum(duration) as duration ,end_date,sum(weight) as weight, sum(electricity_out_duration) as electricity_out_duration, sum(other_prod_blocker_duration) as other_prod_blocker_duration,max(bond_process_id) as bond_process_id,max(piece_per_mould) as piece_per_mould,unit  from bond_production_view where product_type= ? group by end_date having end_date =? ', [$type->name, $todayDate]);
                $data = !empty($tmp)?$tmp[0]:null;
                $tmp  = DB::select('select sum(qty) as qty, sum(rejection_under_size_qty) as rejection_under_size_qty,sum(rejection_over_size_qty) as rejection_over_size_qty,sum(rejection_shape_qty) as rejection_shape_qty , sum(net_qty) as net_qty ,created_date  from qc_view where product_type= ? group by created_date having created_date =? ', [$type->name, $todayDate]);
                $qc = !empty($tmp)?$tmp[0]:null;
                $tmp  = DB::select('select sum(qty) as qty,created_date  from packing_view where product_type= ? group by created_date having created_date =? ', [$type->name, $todayDate]);
                $pk = !empty($tmp)?$tmp[0]:null;
            }else if(!empty($month)){
                $tmp = DB::select('select sum(mould) as mould, sum(remaining_piece) as remaining_piece,sum(duration) as duration,end_month,sum(weight) as weight, sum(electricity_out_duration) as electricity_out_duration, sum(other_prod_blocker_duration) as other_prod_blocker_duration, max(bond_process_id) as bond_process_id,unit,max(piece_per_mould) as piece_per_mould  from bond_production_view where product_type= ? group by end_month having end_month =? ', [$type->name, $month]);
                $data = !empty($tmp)?$tmp[0]:null;
                $tmp  = DB::select('select sum(qty) as qty, sum(rejection_under_size_qty) as rejection_under_size_qty,sum(rejection_over_size_qty) as rejection_over_size_qty, sum(rejection_shape_qty) as rejection_shape_qty, sum(net_qty) as net_qty ,created_date,created_month  from qc_view where product_type= ? group by created_month having created_month =? ', [$type->name, $month]); 
                $qc = !empty($tmp)?$tmp[0]:null;
                $tmp  = DB::select('select sum(qty) as qty,created_date, created_month  from packing_view where product_type= ? group by created_month having created_month =? ', [$type->name, $month]);
                $pk = !empty($tmp)?$tmp[0]:null;
            }
            
            
            if(!empty($data) && $data->mould>0){

                $dItem = new \stdClass();
                $dItem->heading = $heading.$type->name.' mould';
                $dItem->items= array();
                
                $item = new \stdClass();
                if($avg){
                    $item->name = 'Avg Mould Per Day';    
                }else{
                    $item->name = 'Totol Mould';
                }
                $piecePerMould = $data->piece_per_mould;

                $totalMould = $data->mould + (int)$data->remaining_piece/$piecePerMould;

                $item->value= Util::f($totalMould);
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));

                $item = new \stdClass();
                if($avg){
                    $item->name = 'Avg Pieces Per Day';    
                }else{
                    $item->name = 'Totol Pieces';
                }
                

                $tp+=$totalMould*$data->piece_per_mould;
                $elOut = $data->electricity_out_duration;
                $otherBlocker = $data->other_prod_blocker_duration;

                $item->value= Util::f($totalMould*$data->piece_per_mould).' '.$data->unit;
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;

                $totalMould = $data->mould ;
                array_push($dItem->items, ($item));  
                
                $totalDuration = (($data->duration/1000)/3600);
                
                $item = new \stdClass();
                $item->name = 'Total Production Time';
                $item->value= Util::sToTime(($data->duration/1000));
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));  

                $item = new \stdClass();
                $item->name = 'Per Hour Mould';
                $item->value= Util::f($totalMould/ $totalDuration);
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));  

                $item = new \stdClass();
                $item->name = 'Totol Powder Weight';
                $item->value= Util::f($data->weight/1000).' Kg';
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));  

                $dItem->items = collect($dItem->items);
                array_push($dItemArray, $dItem);
            }

            if(!empty($qc) && $qc->net_qty>0){

                $dItem = new \stdClass();
                $dItem->heading = $heading.$type->name.' quality check';
                $dItem->items= array();


                $item = new \stdClass();
                $item->name = 'Totol Qty(without Rejection)';
                $item->value= Util::f($qc->qty);
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));

                $item = new \stdClass();
                $item->name = 'Totol OverSize Rejection';
                $item->value= Util::f($qc->rejection_over_size_qty);
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));
                
                
                $item = new \stdClass();
                $item->name = 'Totol UnderSize Rejection';
                $item->value= Util::f($qc->rejection_under_size_qty);
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));

                $item = new \stdClass();
                $item->name = 'Totol Shape Rejection';
                $item->value= Util::f($qc->rejection_shape_qty);
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));
                
                $item = new \stdClass();
                $item->name = 'Net QC Qty';
                $item->value= Util::f($qc->net_qty);
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));

                $netRej = $qc->rejection_under_size_qty+$qc->rejection_shape_qty+$qc->rejection_over_size_qty;
                $percent = Util::f(($netRej/$qc->qty)*100);

                $item = new \stdClass();
                $item->name = 'Rejection(%)';
                $item->value= ($percent).'%';
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));


                $dItem->items = collect($dItem->items);
                array_push($dItemArray, $dItem);
            }

            if(!empty($pk) && $pk->qty>0){
                $dItem = new \stdClass();
                $dItem->heading = $heading.$type->name.' packing';
                $dItem->items= array();

                $item = new \stdClass();
                $item->name = 'Total Packed Qty';
                $item->value= Util::f($qc->qty);
                $item->s_text = '';
                $item->value_color = self::V_COLOR;
                $item->scolor = self::S_COLOR;
                array_push($dItem->items, ($item));
                $dItem->items = collect($dItem->items);
                array_push($dItemArray, $dItem);
            }

            $section->items = $dItemArray;
        }

        $section->items = collect($dItemArray);
        return $section;
    }



}