<?php

namespace App\Http\Controllers\Frontend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\DummyData as DummyDataModel;
use App\Models\ElementsDensity as ElementsDensityModel;
use App\Models\PetPopularity as PetPopularityModel;
use PDF, Carbon, App, DB, Str;

class PdfDownloadController extends Controller
{
    public function __construct(DummyDataModel $dummyDataModel, ElementsDensityModel $elementsDensityModel, PetPopularityModel $petPopularityModel){
        $this->dummyDataModel = $dummyDataModel;
        $this->elementsDensityModel = $elementsDensityModel;
        $this->petPopularityModel = $petPopularityModel;
    }

    //load the datas on index
    public function index(){
        $this->data['elements'] = $this->get_elements_data();
        $this->data['pet_popularity'] = $this->get_pet_popularity();

    	return view('frontend.pdf_download',$this->data);
    }

    public function download(Request $request){
        $this->data['bar_chart'] = $request->bar_chart;
        $this->data['line_chart'] = $request->line_chart;
    	$this->data['dummy_data'] = $this->dummyDataModel->first();
    	$pdf = App::make('dompdf.wrapper');

    	//set the html view to load
    	$pdf->loadView('domPdf.sample',$this->data);

    	// set the pdf file name
    	// use $pdf->download to download the pdf or use $pdf->stream to display the pdf on your browser
    	return $pdf->download('sample-pdf-'.date('Ymd').'.pdf');
    	// return $pdf->stream('sample-pdf-'.date('Ymd').'.pdf');
        return redirect()->back();
    }

    private function get_elements_data(){
        //the code below depends on how you will represent your data based on your data structure
        $elements = $this->elementsDensityModel->all();
        $elements_data = [];

        $info = ['Element', 'Density',  [ 'role' => 'style' ]];
        array_push($elements_data,$info);

        $color_setting = [
            'copper' => '#ffb1c1',
            'silver' => '#9ad0f5',
            'gold' => '#ffe6aa',
            'platinum' => '#a5dfdf',
        ];

        foreach ($elements as $key => $value) {
            array_push($elements_data,[ Str::title($value->elements), (int)$value->density, $color_setting[$value->elements]]);
        }

        return json_encode($elements_data);
    }

    private function get_pet_popularity(){
        //the code below depends on how you will represent your data based on your data structure
        $dogs = $this->petPopularityModel->where('pet_name','Dogs')->pluck('popularity')->toArray();
        $cats = $this->petPopularityModel->where('pet_name','Cats')->pluck('popularity')->toArray();
        $popularity_data = [];
        foreach(range(0,(count($dogs)-1 > count($cats)-1? count($dogs)-1 : count($cats)-1 )) as $value){
            array_push($popularity_data,[$value,(int)$dogs[$value],(int)$cats[$value]]);
        }
        return json_encode($popularity_data);
    }
}
