<?php

namespace App\Http\Controllers;

use App\User;
use App\sample_file;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\Types\Null_;

class sample_fileController extends Controller
{
  public function __construct()
    {
        $this->middleware(['auth', 'verified', 'pass']);
//        ->except(['create', 'store'])
    }
    
    public function index(Request $request){
      // $date1 = null;
      // $date1 = Carbon::now()->subYear()->format('Y');
      $date1 = Carbon::now()->format('Y');
      $date = (!empty($_GET["date"])) ? ($_GET["date"]) : ($date1);
      $sex = (!empty($_GET["gender"])) ? ($_GET["gender"]) : 'all';

      // return $sex.' '.$date;
      
      $data = sample_file::distinct()->orderBy('year', 'desc')->get(['year']);

        // $sex = 'm';
        
        
      if(!empty($_GET["gender"]) OR !empty($_GET["date"])){

              if(($sex != 'all') AND ($date != 'all')){
                $result = DB::select("SELECT country, year, sex, age, specimen,
                SUM(value) AS value
                FROM sample_files
                WHERE sex = '$sex' AND year = '$date'
                GROUP BY country, year, sex, age, specimen ");
                }

              elseif(($sex == 'all') AND ($date != 'all')){
                $result = DB::select("SELECT country, year, sex, age, specimen,
                SUM(value) AS value
                FROM sample_files
                WHERE year = '$date'
                GROUP BY country, year, sex, age, specimen ");
              }

              elseif(($sex != 'all') AND ($date == 'all')){
                $result = DB::select("SELECT country, year, sex, age, specimen,
                SUM(value) AS value
                FROM sample_files
                WHERE sex = '$sex'
                GROUP BY country, year, sex, age, specimen ");
              }
              else{
                $result = DB::select("SELECT country, year, sex, age, specimen,
                SUM(value) AS value
                FROM sample_files
                GROUP BY country, year, sex, age, specimen ");
              }
      } else{
        $result = DB::select("SELECT country, year, sex, age, specimen,
        SUM(value) AS value
        FROM sample_files
        where year = '$date'
        -- where sex = '$sex'
        GROUP BY country, year, sex, age, specimen");
      }

    return view('pages.sample_file')
    ->with('sample_file', $result)
    ->with('data', $data)
    ->with('date', $date)
    ->with('sex', $sex);

    }
}
