<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use App\Models\Rating;
use App\Models\User;
use App\Models\Company;

class RatingController extends Controller
{
    public function __construct()
    {
        //
        // $this->middleware('auth:admin');

       // $adminUser = auth()->guard('admin')->user();

        //if (!$adminUser)
        //{
          //  return response()->json(['error' => 'Unauthorized.'], 401);
        //}

    }

    public function save(Request $request)
    {
    	 # echo "<pre>";
    	 # var_dump($request);
    	 # die;

    	 # $user_id = $request->user_id;
    	 # $company_id = $request['company_id'];


    	$email = $request->email;
    	$user = User::where('email', $email)->first();

    	if(!$user){
    		return response()->json(['error' => 'No user found'], 404);
    	}

    	$user_id = $user->id;
    	$company_id = $user->company_id;

    	#var_dump($company_id);die;
    	$rating_1 = $request->rating_1;
    	$rating_2 = $request->rating_2;
    	$rating_3 = $request->rating_3;
    	$rating_4 = $request->rating_4;

    	$all_rates = [];

    	$all_rates[] = ['rate' => $rating_1, 'type' => 1, 'user_id' => $user_id, 'company_id' => $company_id];
    	$all_rates[] = ['rate' => $rating_2, 'type' => 2, 'user_id' => $user_id, 'company_id' => $company_id];
    	$all_rates[] = ['rate' => $rating_3, 'type' => 3, 'user_id' => $user_id, 'company_id' => $company_id];
    	$all_rates[] = ['rate' => $rating_4, 'type' => 4, 'user_id' => $user_id, 'company_id' => $company_id];

    	foreach ($all_rates as $k => $v) 
    	{
    		# $check = new Rating();
    		// $check = Rating::where([
    		// 	['user_id', $user_id],
    		// 	['company_id', $company_id],
    		// 	['type', $v['type']]
    		// ])->first();
    		
    		// if ($check && $check->id > 0) {

    		// 	$check->rate = $v['rate'];
    		// 	$check->save();

    		// }else{

    			$rating = Rating::create([
    				'rate' => $v['rate'],
    				'type' => $v['type'],
    				'user_id' => $user_id,
    				'company_id' =>  $company_id
        		]);

        		$rating->save();

    		// }
    	}

    	return response()->json(['status' => 'ok', 'info' => 'all done'], 200);
    }


    public function listAll(Request $request)
    {
    	$company_id = 0;
    	if (isset($request->company_id)) {
    		$company_id = $request->company_id;

    		$all_ratings = Rating::where('company_id', $company_id)->get();

    		$ratings_by_users = [];
    		# $ratings_by_users['list'] = [];
    		# $ratings_by_users['user'] = null;
            $ratings_by_users['count'] = 0;

            $ratings_by_users['average'] = [];
            $ratings_by_users['average'][1]['sum'] = 0;
            $ratings_by_users['average'][1]['count'] = 0;

            $ratings_by_users['average'][2]['sum'] = 0;
            $ratings_by_users['average'][2]['count'] = 0;

            $ratings_by_users['average'][3]['sum'] = 0;
            $ratings_by_users['average'][3]['count'] = 0;

            $ratings_by_users['average'][4]['sum'] = 0;
            $ratings_by_users['average'][4]['count'] = 0;


            $regroup = [];

            foreach ($all_ratings as $k => $v) 
            {
                $regroup[ $v['user_id'] ."_". $v['company_id'] ."_".$v['type'] ][ $v['created_at']->toDateTimeString() ] = $v; 
            }


    		foreach ($regroup as $kk => $vv) {
                foreach ($vv as $k => $v) {

        			$user = User::find($v['user_id']);
        			if($user)
        				{
                            # var_dump($v['type']);
        					$user->only('first_name', 'last_name');
        					$ratings_by_users['list'][ $v['user_id'] ][ $k ]['user'] = $user;
        					$ratings_by_users['list'][ $v['user_id'] ][ $k ]['ratings'][ $v['type'] ] = $v['rate'];
                            $ratings_by_users['average'][ $v['type'] ]['sum'] += intval($v['rate']); 
                            $ratings_by_users['average'][ $v['type'] ]['count'] += 1;


        				}
                }
                $ratings_by_users['count'] += 0.25; 
    		}

            # foreach ($ratings_by_users['list'] as $key => $value) {
            #    $ratings_by_users['count'] += count($value);
            # }


    		# var_dump($all_ratings);die();
    		return response()->json($ratings_by_users, 200);

    	}else{
    		return response()->json(['error' => 'I need a Company Id'], 404);
    	}
    }

    public function latestReview(Request $request)
    {

            $last_rate = Rating::where('id', '>', 0)->latest();

            $ratings_by_users = [];
            $ratings_by_users['list'] = [];
            $ratings_by_users['user'] = null;

            $ratings_by_users['average'] = [];
            $ratings_by_users['average'][1]['sum'] = 0;
            $ratings_by_users['average'][1]['count'] = 0;

            $ratings_by_users['average'][2]['sum'] = 0;
            $ratings_by_users['average'][2]['count'] = 0;

            $ratings_by_users['average'][3]['sum'] = 0;
            $ratings_by_users['average'][3]['count'] = 0;

            $ratings_by_users['average'][4]['sum'] = 0;
            $ratings_by_users['average'][4]['count'] = 0;

            
            $user = User::find($last_rate['user_id']);
            if($user)
                {
                    $user->only('first_name', 'last_name');
                    $ratings_by_users['list'][ $last_rate['user_id'] ]['user'] = $user;
                    $ratings_by_users['list'][ $last_rate['user_id'] ]['ratings'][ $last_rate['type'] ] = $last_rate['rate'];
                    $ratings_by_users['average'][ $last_rate['type'] ]['sum'] += intval($last_rate['rate']); 
                    $ratings_by_users['average'][ $last_rate['type'] ]['count'] += 1; 

                }


            # var_dump($all_ratings);die();
            return response()->json($ratings_by_users, 200);

    }

    function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
        // open raw memory as file so no temp files needed, you might run out of memory though
        $f = fopen('php://memory', 'w'); 
        // loop over the input array
        foreach ($array as $line) { 
            // generate csv lines from the inner arrays
            fputcsv($f, $line, $delimiter); 
        }
        // reset the file pointer to the start of the file
        fseek($f, 0);
        // tell the browser it's going to be a csv file
        header('Content-Type: text/csv');
        // tell the browser we want to save it instead of displaying it
        header('Content-Disposition: attachment; filename="'.$filename.'";');
        // make php send the generated csv lines to the browser
        fpassthru($f);
    }

    public function export(Request $request)
    {
        $all = Rating::where('id', '>', 0)->get();

        $export_obj = [];
        $export_obj_csv = [];
        
        // 'Sei soddisfatto del prodotto Aviointeriors?',
        // 'Sei soddisfatto del Lead Time?',
        // 'Sei soddisfatto del Customer Support?',
        // 'Sei soddisfatto del Technical Support?',

        $export_obj_csv[] = [
            'Comapany name',
            'User',
            'Are you satisfied with the Aviointeriors product?',
            'Are you satisfied with the Lead Time?',
            'Are you satisfied with Customer Support?',
            'Are you satisfied with the Technical Support?',
            'Data Recensione'
        ];


        if ($all) {
            $regroup = [];
            foreach ($all as $k => $v) {

                $rate_date = $v['created_at']->toDateTimeString();

                $regroup[ $v['user_id'] ]['rates'][$rate_date][ $v['type'] ] = $v['rate']; 
                $regroup[ $v['user_id'] ]['info'][$rate_date] = $v; 
            }

            foreach ($regroup as $k => $v) {

                # echo "<pre>";
                # var_dump($v);die();

                foreach ($v['info'] as $k_info_data => $v_info) {

                    $user = User::find($v_info['user_id']);
                    $company = Company::find($v_info['company_id']);

                    $user_first_name = '';
                    $user_last_name = '';
                    $company_name = '';

                    if ($user) {
                        $user_first_name = $user['first_name'];
                        $user_last_name = $user['last_name'];
                    }

                    if ($company) {
                        $company_name = $company['name'];
                    }

                    if ($user && $company) {

                            # echo "<pre>";
                            # var_dump($vv);die;

                            # $export_obj[ $company_name ][ $user_first_name.' '.$user_last_name ][ $v_info['type'] ] = $v_info['rate'];

                            $export_obj_csv[] = [
                                $company_name,
                                $user_first_name.' '.$user_last_name,
                                $v['rates'][ $k_info_data ][1],
                                $v['rates'][ $k_info_data ][2],
                                $v['rates'][ $k_info_data ][3],
                                $v['rates'][ $k_info_data ][4],
                                $k_info_data
                            ];                        
                    }
                }

            }
        }

        $this->array_to_csv_download(
          $export_obj_csv,
          "export.csv"
        );
        die();
        # return response()->json($export_obj, 200);
    }


}
