<?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 Illuminate\Http\Response;
use PDF, Carbon, App, DB, Str, ZipArchive, File;

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->createFolder();
        $files = [];
        foreach ($request->bar_chart as $key => $value) {
            $this->data['bar_chart'] = $request->bar_chart[$key];
            $this->data['line_chart'] = $request->line_chart[$key];
            $pdf = new PDF();
            $pdf = App::make('dompdf.wrapper');
            //set the html view to load
            $pdf->loadView('domPdf.sample',$this->data)->save( public_path('pdf/sample-pdf-'.$key.'-'.date('Ymd').'.pdf') );
            $filePath = public_path('pdf/sample-pdf-'.$key.'-'.date('Ymd').'.pdf');
            // $pdf->download('sample-pdf-'.date('Ymd').'.pdf');
            array_push($files,$filePath);
        }
        $zipname = 'sample-pdf-download-'.date('Ymd').'.zip';
        $zip = new ZipArchive;
        $zip->open($zipname, ZipArchive::CREATE);
        foreach ($files as $key => $file) {
            $zip->addFile($file,'sample-pdf-'.$key.'-'.date('Ymd').'.pdf');
        }
        $zip->close();
        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename='.$zipname);
        header('Content-Length: ' . filesize($zipname));
        readfile($zipname);
    	// 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->stream('sample-pdf-'.date('Ymd').'.pdf');
        return redirect()->back();
    }

    private function getMonths($type){
        switch ($type) {
            case 'elements':
                return $this->elementsDensityModel->orderBy('created_at','desc')
                                        ->get()
                                        ->groupBy(function (ElementsDensityModel $item) {
                                            return $item->created_at->format('Y-m');
                                        });
                break;

            default:
                return $this->petPopularityModel->orderBy('created_at','desc')
                                        ->get()
                                        ->groupBy(function (PetPopularityModel $item) {
                                            return $item->created_at->format('Y-m');
                                        });
                break;
        }
    }

    private function get_elements_data(){
        //the code below depends on how you will represent your data based on your data structure
        $elements_data = [];
        foreach ($this->getMonths('elements') as $index => $month) {
            $start = date('Y-m-d',strtotime($index));
            $end = date('Y-m-t',strtotime($index));

            $small_data = [];
            $elements = $this->elementsDensityModel->whereBetween('created_at',[$start,$end])->get();
            $info = ['Element', 'Density',  [ 'role' => 'style' ]];
            array_push($small_data,$info);
            $color_setting = [
                'copper' => '#ffb1c1',
                'silver' => '#9ad0f5',
                'gold' => '#ffe6aa',
                'platinum' => '#a5dfdf',
            ];
            foreach ($elements as $key => $value) {
                array_push($small_data,[ Str::title($value->elements), (int)$value->density, $color_setting[$value->elements]]);
            }
            array_push($elements_data,[ 'date' => $index,'elements' => json_encode($small_data)]);
        }
        return $elements_data;
    }

    private function get_pet_popularity(){
        //the code below depends on how you will represent your data based on your data structure
        $popularity_data = [];
        foreach ($this->getMonths('popularity') as $index => $month) {
            $start = date('Y-m-d',strtotime($index));
            $end = date('Y-m-t',strtotime($index));

            $small_data = [];
            $dogs = $this->petPopularityModel->where('pet_name','Dogs')->whereBetween('created_at',[$start,$end])->pluck('popularity')->toArray();
            $cats = $this->petPopularityModel->where('pet_name','Cats')->whereBetween('created_at',[$start,$end])->pluck('popularity')->toArray();
            foreach(range(0,(count($dogs)-1 > count($cats)-1? count($dogs)-1 : count($cats)-1 )) as $value){
                array_push($small_data,[$value,(int)$dogs[$value],(int)$cats[$value]]);
            }
            array_push($popularity_data,[ 'date' => $index, 'popularity' => json_encode($small_data)]);
        }
        return $popularity_data;
    }

    private function createFolder(){
        $path = public_path('pdf');
        File::makeDirectory($path, $mode = 0777, true, true);
    }
}
