<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\TypeOfCancer;
use App\User;
use App\ClientList;
use DB;
use Validator;
Use Carbon\Carbon;

class PagesController extends Controller
{
    public function home()
    {

        $cancers = TypeOfCancer::all();
        return view ('welcome', [
            'foo' => 'bar'
        ])->with(compact('cancers'));
    }


    public function contact()
    {
        return view ('contact');
    }


    public function dashboard()
    {
        return view ('dashboard');
    }
    // function to geocode address, it will return false if unable to geocode address
    public function geocode($address)
    {
        
        
         
            // url encode the address
            $address = urlencode($address);
             
            // google map geocode api url
            $url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=AIzaSyBKv-nqU0R2ytMg315H2tQKgmHF57Hf2gk";
         
            // get the json response
            $resp_json = file_get_contents($url);
             
            // decode the json
            $resp = json_decode($resp_json, true);
         
            // response status will be 'OK', if able to geocode given address 
            if($resp['status']=='OK'){
         
                // get the important data
                $lati = isset($resp['results'][0]['geometry']['location']['lat']) ? $resp['results'][0]['geometry']['location']['lat'] : "";
                $longi = isset($resp['results'][0]['geometry']['location']['lng']) ? $resp['results'][0]['geometry']['location']['lng'] : "";
                
                 
                // verify if data is complete
                if($lati && $longi ){
                    $data_arr = $lati.",".$longi;            
                    return $data_arr;
                     
                }else{
                    return false;
                }
            }
         
            else{
                // echo "<strong>ERROR: {$resp['status']}</strong>";
                return false;
            }
        
    }

    public function addEnquiry(Request $request){
        $validation = Validator::make($request->all(),[
            'fname' => 'required',
            'email' => 'email|required|unique:client_list,email',
            'phone' => 'numeric|required',
        ])->validate();
        $client= new ClientList;
        $client->name=$request->fname.' '.$request->lname;
        $client->email=$request->email;
        $client->phone=$request->phone;
        $client->age=$request->age;/*date("Y-m-d", strtotime($request->age));*/
        $client->type=$request->type;
        $client->address=$request->address;
        $client->zip=$request->zip;
        $client->state=$request->state;
      
        if($request->address!==false)
        {
            $client->geocode = $this->geocode($request->address.",".$request->zip);
        }
        $client->save();
        if($client){
            $response = 'success';
        }else{
            $response = 'failed';
        }
        return response()->json($response);
        
    }
    public function getGeoCode()
    {
        $geo_codes=ClientList::where('geocode','!=',0)->pluck('geocode');
       
        foreach ($geo_codes as $key => $value) {
            $ar=explode(',', $value);
            if ( (array_key_exists(0,$ar)) && (array_key_exists(1,$ar)) ) 
            {

                $geocode[$key][0]=$ar[0];
                $geocode[$key][1]=$ar[1];
            }
        }
       
        return response()->json(['geocode'=>$geocode]);
    }
    public function getchart1()
    {
        $user_info = ClientList::select('age')->get();

                  //dd($user_info);
        foreach ($user_info as $key => $value) 
        {
            # procedural
            $ages[]= date_diff(date_create($value->age), date_create('today'))->y;
        }         
            $total=array_count_values($ages);
            $s=[];
            foreach ($total as $key => $value) {
                for ($i=1; $i < 101 ; $i++) 
                { 
                    $end=$i+9;
                    if( ($key >= $i) && ($key <= $end) )
                    {
                        if(isset($s[$i.'-'.$end]))
                        {
                            $s[$i.'-'.$end] += 1;  
                        }
                        else
                        {
                            $s[$i.'-'.$end]= $value;
                        }
                    }
                    $i=$end;
                }
            }
            ksort($s);
            
           
        return response()->json(['total'=>$s]);
       
       
    }
    public function getPieChart()
    {
      
        $user_info = ClientList::select('type', DB::raw('count(*) as total'))
                 ->groupBy('type')
                 ->get();
                 // dd($user_info);
        foreach ($user_info as $key => $value) 
        {
                $name=TypeOfCancer::find($value['type']);

                $cancer[]=$name->name;
                $total[]=($value['total']);
        }         
        // $result=array_combine($cancer, $total);
        return response()->json(['type'=>$cancer,'values'=>$total]);
    }

}
