<?php

namespace App\Http\Controllers\Report;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Task;
use App\Models\Project;
use App\Models\EmployeeTask;
use App\Models\Employee;
use App\User;
use PDF;

class ReportController extends Controller
{
    public function over_due_tasks(Request $request){
    	// dd($request);
        $data['title'] = "Over Due Tasks Report";
        $data['request'] = $request;
        $data['menu'] = "report";
        $data['sub_menu'] = "over_due_tasks";
        $data['users'] = User::all();
        $data['projects'] = Project::where('status', 1)->get();
        $data['employees'] = Employee::where('status', 1)->get();
        $tasks = Task::orderBy('id','desc')->whereNotNull('done_date');
        
        if($request->daterange){
            $daterange = explode(' - ', $request->daterange);
            $start_date = ($daterange[0])? date('Y-m-d', strtotime($daterange[0])) : ''; 
            $end_date = ($daterange[1])? date('Y-m-d', strtotime($daterange[1])) : ''; 
            if($start_date && $end_date){
                $tasks = $tasks->whereBetween('start_date', [$start_date, $end_date]);
            }
            $data['date_show'] = ($start_date == $end_date)? date('M d y', strtotime($start_date)) : date('M d y', strtotime($start_date)) .' - '. date('M d y', strtotime($end_date));
        }
        if($request->project){
            $tasks = $tasks->where('project_id', $request->project);
        }
        if($request->employee){
            $emp_task = EmployeeTask::where('employee_id', $request->employee)->get()->toArray();
            $ids = array_column($emp_task, 'task_id');
            $tasks = $tasks->whereIn('id', array_unique($ids));
        }
        if($request->asign_by){
            $tasks = $tasks->where('created_by', $request->asign_by);
        }

        if($request->sub_type == 'export'){
            set_time_limit(300);
            $data['tasks'] = $tasks->get();
            $pdf = PDF::loadView('pages.report.print.over_due_tasks_print', $data);
            return $pdf->stream('over_due_tasks_report.pdf');
        }else{
            $data['tasks'] = $tasks->paginate(20);
            return view('pages.report.over_due_tasks', $data);
        }
    }
}
