<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;

class ReportController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function showReportList()
    {
        $oldesDate = DB::select("SELECT `year`, `month` FROM storage WHERE tenant = " . (int)session("current_tenant_id") . " ORDER BY `date` ASC  LIMIT 1;");
        if(count($oldesDate) == 0) {
            return view("dashboard.reports", ["avalibleReports" => []]);
        }
        $oldesDate = $oldesDate[0];
        $avalibleReports = [];
        for ($i = $oldesDate->year; $i <= date("Y"); $i++) {
            for ($m = 1; $m <= 12; $m++) {
                if($i == $oldesDate->year && $m < $oldesDate->month) {
                    continue;
                }
                if($i == date("Y") && $m > date("m")) {
                    continue;
                }
                $avalibleReports[] = ["year" => $i, "month" => $m];
            }
        }

        return view("dashboard.reports", ["avalibleReports" => $avalibleReports]);
    }

    public function spaceReport($year, $month) {
        $reportData = DB::select("SELECT * FROM storage WHERE tenant = ".(int)session("current_tenant_id")." AND `year` = ".(int)$year." AND `month` = ".(int)$month.";");
        $report = "year;month;day;hour;gallery;size\n";
        foreach ($reportData as $reportLine) {
            $report .= $reportLine->year.";".$reportLine->month.";".$reportLine->day.";".$reportLine->hour.";".$reportLine->gallery.";".$reportLine->size."\n";
        }

        $res = new Response();
        $res->header("Content-type", "text/csv");
        $res->header("Content-Disposition", "attachment; filename=".$year."_".$month."_space.csv");
        $res->setContent($report);
        return $res;
    }

    public function trafficReport($year, $month) {
        $reportData = DB::select("SELECT * FROM traffic WHERE tenant = ".(int)session("current_tenant_id")." AND `year` = ".(int)$year." AND `month` = ".(int)$month.";");
        $report = "year;month;day;hour;gallery;typ;traffic\n";
        foreach ($reportData as $reportLine) {
            $report .= $reportLine->year.";".$reportLine->month.";".$reportLine->day.";".$reportLine->hour.";".$reportLine->gallery.";".$reportLine->typ.";".$reportLine->traffic."\n";
        }

        $res = new Response();
        $res->header("Content-type", "text/csv");
        $res->header("Content-Disposition", "attachment; filename=".$year."_".$month."_trafficg.csv");
        $res->setContent($report);
        return $res;
    }

}
