<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\User;
use App\Models\Project;
use App\Models\Task;
use App\Models\AssignProject;
use Hash;
use Mail;
use DB;
use App\Models\FundRequest;
use App\Models\AccountHead;
use App\Models\Attendance;
use Excel;
use Auth;
class ApiController extends Controller
{
    
    public function get_all_users()
    {
        $users = User::all();
        $new_array=array('users'=>$users);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    public function get_all_projects()
    {
        $projects   =   Project::all();
        $new_array=array('projects'=>$projects);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }

    public function get_all_tasks()
    {
        $tasks=Task::with(['user','proj_name'])->where('user_id','!=',0)->where('created_by','!=',0)->where('assign_by','!=',0)->orderBy('created_time')->get();
        foreach($tasks as $task)
        {
            if($task->status == 1)
            {
                $status =   "Created";
            } 
            else if($task->status == 2)
            {
                $status =   "In process";
            } 
            else if($task->status == 3)
            {
                $status =   "Completed";
            } 
            else if($task->status == 4)
            {
                $status =   "Checking";
            } 
            else if($task->status == 5)
            {
                $status =   "Bugfixing";
            } 
            else if($task->status == 6)
            {
                $status =   "done";
            }
            $task_array[]   =   array(
                                    'name'          =>  $task['name'],
                                    'description'   =>  $task['description'],
                                    'project_name'  =>  @$task->proj_name->name,
                                    'user_name'     =>$task->user->name,
                                    'created_by'    =>  $task->user->name,
                                    'assign_by'     =>$task->user->name,
                                    'created_time'  =>  $task['created_time'],
                                    'dead_line'     =>  $task['dead_line'],
                                    'priority'      =>  $task['priority'],
                                    'assign_time'   =>  $task['assign_time'],
                                    'start_time'    =>  $task['start_time'],
                                    'closing_time'  =>  $task['closing_time'],
                                    'estimated_time'=>  $task['estimated_time'],
                                    'status'        =>  $status,
                                );
        }
        $new_array=array('tasks'=>$task_array);
        return json_encode($new_array,JSON_PRETTY_PRINT);
        
    }
    public function deadline_missed()
    {
        $deadline_missed=Task::with(['user','proj_name'])->where('user_id','!=',0)->where('status','!=',6)->whereDate('dead_line', '<', date('Y-m-d'))->orderBy('created_time')->get();
        //dd($deadline_missed);
        
        foreach($deadline_missed as $task)
        {
            if($task->status == 1)
            {
                $status =   "Created";
            } 
            else if($task->status == 2)
            {
                $status =   "In process";
            } 
            else if($task->status == 3)
            {
                $status =   "Completed";
            } 
            else if($task->status == 4)
            {
                $status =   "Checking";
            } 
            else if($task->status == 5)
            {
                $status =   "Bugfixing";
            } 
            else if($task->status == 6)
            {
                $status =   "done";
            }
            $task_array[]   =   array(
                                    'task_id'       =>  $task['id'],
                                    'name'          =>  $task['name'],
                                    'description'   =>  $task['description'],
                                    'project_name'  =>  @$task->proj_name->name,
                                    'user_name'     =>  $task->user->name,
                                    'created_by'    =>  $task->user->name,
                                    'assign_by'     =>  $task->user->name,
                                    'created_time'  =>  $task['created_time'],
                                    'dead_line'     =>  $task['dead_line'],
                                    'priority'      =>  $task['priority'],
                                    'assign_time'   =>  $task['assign_time'],
                                    'start_time'    =>  $task['start_time'],
                                    'closing_time'  =>  $task['closing_time'],
                                    'estimated_time'=>  $task['estimated_time'],
                                    'status'        =>  $status,
                                );
        }
        $new_array=array('deadline_missed'=>$task_array);
        return json_encode($new_array,JSON_PRETTY_PRINT);             
    }
    public function no_work_today()
    {
        $all_users=User::where('utype','=',2)->pluck('name','id');
        $working_today = Task::where('user_id','!=',0)->whereDate('start_time', '=', date('Y-m-d'))->orwhereDate('closing_time', '=', date('Y-m-d'))->whereNotIn('status',[2,3,4,5])->orderBy('created_time')->pluck('user_id');
        
        $active_users=array();
        foreach($working_today as $row){
            if($row !=0){
                if (!in_array($row,$active_users))
                {
                    array_push($active_users,$row);
                }
            }
        }
        $inactive_users=array();
        foreach($all_users as $i=>$value){
           
            if (!in_array($i,$active_users))
            {
                array_push($inactive_users,$value);
            }
        }
        $new_array=array('not_working_today'=>$inactive_users);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    public function create_task(Request $request)
    {
        $name = $request->name;
        $proj_id = $request->proj_id;
        $description = $request->description;
        $estimated_time = $request->dead_line;
        $task_type = 1;
        $priority = $request->priority;
        $dead_date = $request->dead_line;
        $assigned_user = $request->user_id;
        $dead_line = $dead_date;
        
        date_default_timezone_set("Asia/Dhaka"); 
        $cdate = date('Y-m-d H:i:s');

        $sav = new Task;
        $sav->name = $name;
        $sav->type = $task_type;
        $sav->proj_id = $proj_id;
        $sav->priority = $priority;
        $sav->dead_line = $dead_line;
        $sav->description = $description;
        $sav->created_time = $cdate;
        $sav->created_by = 2;
        $sav->status = 1;
        $sav->user_id=$assigned_user;
        $sav->assign_by = 2;
        $sav->assign_time = $cdate;
        $sav->save();

        $task_id = $sav->id;

        $proj_user = AssignProject::where('proj_id',$proj_id)->get();
        /*
        $proj_namee = Project::find($proj_id)->name;

        foreach($proj_user as $pu){
            $data = [
                'task_name' => $name,
                'proj_name' => $proj_namee,
                'user_name' => $pu->one_user->name,
                'details'   => $description,
            ];

            $subj = "A task has been created in ".$proj_namee.".";

            $this->send_email_new_task($pu->one_user->email,$subj,$data);
        }*/
        if($task_id !='' && $task_id !=0){
            $new_array=array('success_message'=>'Successfully Saved');
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
        else 
        {
            $new_array=array('unsucessful_message'=>'Unsuccessful Attempt!Try Again!');
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
        
    }
    public function send_email_new_task($uemail,$subj,$data)
    {

        Mail::send('emails.new_task', $data, function ($message) use ($uemail,$subj)
        {
            $message->from('m.revinr@gmail.com', 'Revinr Task Management');
            $message->to($uemail)->subject($subj);
        });
    }
    public function change_task_status($id)
    {
        $new_value;
        $msg;
        $start_time;
        $end_time;
        $prv_value=DB::table('task')->where('id','=',$id)->first();
        if($prv_value->status >= 1 && $prv_value->status < 6)
        {
            $new_value= 6;
            $end_time = date('Y-m-d H:i:s');
        }
        if($new_value ==6){
           DB::table('task')->where('id','=',$id)->update(array('status'=>$new_value,'closing_time'=>$end_time)); 
        }
        /*if($prv_value->status==1)
        {
            $new_value= 2;
            date_default_timezone_set("Asia/Dhaka"); 
            $start_time = date('Y-m-d H:i:s');
        }
        else if($prv_value->status > 1 && $prv_value->status < 6)
        {
            $new_value= 6;
            $end_time = date('Y-m-d H:i:s');
        } 
        if($new_value==2){
            DB::table('task')->where('id','=',$id)->update(array('status'=>$new_value,'start_time'=>$start_time));
        } else if($new_value ==6){
           DB::table('task')->where('id','=',$id)->update(array('status'=>$new_value,'closing_time'=>$end_time)); 
        }*/

        $new_array=array('success_message'=>'Successfully Status Changed');
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    public function fund_purpose()
    {
        $fund_purpose   =   AccountHead::where('type_id',2)->where('parent_head',24)->orderBy('name','asc')->get();
        foreach($fund_purpose as $fund)
        {
            $fund_p[]   =   array(
                                    'id'            =>  $fund->id,
                                    'name'          =>  $fund->name,
                                );
        }
        $new_array=array('fund_purpose'=>$fund_p);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    public function fund_save(Request $req)
    {
        $this->validate($req,[
            'purpose'=>'required',
            'amount'=>'required|numeric'
        ]);

        $fund=new FundRequest();
        $fund->purpose=$req->get('purpose');
        $fund->description=$req->get('description');
        $fund->amount=$req->get('amount');
        $fund->due_date=$req->get('due_date',date('Y-m-d H:i:s'));
        $fund->request_by=2;
        $fund->is_approved=0;
        $fund->save();
        if($fund->id > 0)
        {
            $new_array=array('success_message'=>'Successfully Saved');
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
    }
    public function get_entry_time_today()
    {
        date_default_timezone_set("Asia/Dhaka");    
        $entry_time =   Attendance::whereDate('attendance_time', '=', date('Y-m-d'))->where('status','=',0)->orderBy('attendance_time','desc')->get();
        $new_array=array('entry_time'=>$entry_time);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    public function get_exit_time_yesterday()
    {
        $exit_time =   Attendance::whereDate('attendance_time', '=', date('Y-m-d',strtotime('yesterday')))->where('status','=',1)->orderBy('attendance_time','desc')->groupBy('attendance_time')->get();
        $new_array=array('exit_time'=>$exit_time);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }

    public function get_month_attendance_report()
    {
        

            $entry_time =   Attendance::whereDate('attendance_time', '=', date('Y-m-d'))->where('status','=',0)->orderBy('attendance_time','desc')->groupBy('attendance_time')->get();
            $exit_time =   Attendance::whereDate('attendance_time', '=', date('Y-m-d',strtotime('yesterday')))->where('status','=',1)->orderBy('attendance_time','desc')->groupBy('attendance_time')->get();
            $title  =   "User Attendace";
            $all_dates  =   array();
            $dates      =   Attendance::pluck('attendance_time');
            $all_users  =   array();
            $users      =   Attendance::pluck('user_id');
            
            $a=strtotime('9:30 am');
            $c=date('H:i:s a', $a);
            $exact_time= $c;
            foreach($users as $user)
            {
                $new_val    =   $user;
                if(!in_array($new_val,$all_users))
                {
                    array_push($all_users, $new_val);
                }
            }
            $late_array = array();
            
            
            foreach($all_users as $d)
            {
            if($d !=6 && $d !=10){
                    $late_count=0;
                    
                    $test_entry_time=Attendance::select('attendance_time','user_name')->where('user_id','=',$d)->where('status','=',0)->whereMonth('attendance_time', '>=', date('m'))->get();
                    $absent_count=Attendance::where('user_id','=',$d)->whereMonth('attendance_time', '=', date('m'))->where('absent_count','=',1)->count();
                    foreach ($test_entry_time as $value1) {
                        $u_name=$value1->user_name;
                        $et=date('H:i:s a',strtotime($value1->attendance_time));
                        if($et>$exact_time)
                        {
                             $late_count++;
                        }
                    }
                    $new_array=array('user_id'=>$d,'user_name'=>@$u_name,'late_count'=>$late_count,'absent_count'=>$absent_count);
                    array_push($late_array, $new_array);
             }  
            }
        
        $new_array=array('late_absent_record'=>$late_array);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    function get_month_report($id)
    {
    
        $entry_times =   Attendance::where('user_id','=',$id)->where('status','=',0)->whereMonth('attendance_time', '=', date('m'))->orderBy('attendance_time','desc')->groupBy('attendance_time')->get();
        $exit_times =   Attendance::where('user_id','=',$id)->where('status','=',1)->whereMonth('attendance_time', '=', date('m'))->orderBy('attendance_time','desc')->groupBy('attendance_time')->get();
        
            foreach($entry_times as $report)
            {
                
                    $entry_array[] = array(
                            'user_id'=>@$report->user_id,
                            'user_name'=>$report->user_name,
                            'time'=>$report->attendance_time
                    );
                    
            }
            
            foreach($exit_times as $report)
            {
                
                    $exit_array[] = array(
                            'user_id'=>@$report->user_id,
                            'user_name'=>$report->user_name,
                            'time'=>$report->attendance_time
                    );
                    
            }
            $report_array=array('entry_array'=>@$entry_array,'exit_array'=>@$exit_array);
        
        $new_array=array('month_attendance_report'=>@$report_array);
        return json_encode(array('month_attendance_report'=>$report_array),JSON_PRETTY_PRINT);
        
    }
    function get_fund_requests()
    {
        $fund_reqs  =   FundRequest::with(['acc_head','user'])->where('is_approved',0)
        ->orderBY('id','desc')->get();
        foreach($fund_reqs as $req)
        {
            $id         =   $req->id;
            $purpose        =   $req->acc_head?$req->acc_head->name:'';
            $description    =   $req->description;
            $created_at     =   $req->created_at;
            $user           =   $req->user?$req->user->name:'';
            $due_date       =   $req->due_date;
            $amount         =   $req->amount;
            $req_array[]    =   array(
                'id'=>$id,
                'created_by'=>$user,
                'purpose'=>$purpose,
                'description'=>$description,
                'created_at'=>$created_at,
                'due_date'=>$due_date,
                'amount'=>$amount
            );
        }
        $new_array=array('fund_requests'=>$req_array);
        return json_encode($new_array,JSON_PRETTY_PRINT); 
    }
    function change_fund_request_status($id,$value)
    {
        
        if($value==1)
        {
            DB::table('fund_request')->where('id','=',$id)->update(array('is_approved'=>$value));
            $new_array=array('message'=>'Fund Request Approved');
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
        else
        {
            DB::table('fund_request')->where('id','=',$id)->delete();
            $new_array=array('message'=>'Fund Request Declined');
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
        
        
    }
    
    
    public function get_pending_tasks()
    {
        $pending_tasks=Task::with(['user','proj_name'])->where('user_id','!=',0)->where('status','!=',6)->orderBy('created_time')->get();
        foreach($pending_tasks as $task)
        {
            
            $task_array[]   =   array(
                        'task_id'       =>  $task['id'],
                        'name'          =>  $task['name'],
                        'description'       =>  $task['description'],
                        'project_name'      =>  @$task->proj_name->name,
                        'user_name'     =>  $task->user->name,
                        'created_by'        =>  $task->user->name,
                        'assign_by'     =>  $task->user->name,
                        'created_time'      =>  $task['created_time'],
                        'dead_line'     =>  $task['dead_line'],
                        'priority'      =>  $task['priority'],
                        'assign_time'       =>  $task['assign_time'],
                        'start_time'        =>  $task['start_time'],
                        'closing_time'      =>  $task['closing_time'],
                        'estimated_time'    =>  $task['estimated_time'],
                    );
        }
        $new_array=array('pending_tasks'=>$task_array);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    
    
    public function get_in_progress_tasks(){
        $in_progress_tasks=Task::with(['user','proj_name'])->where('user_id','!=',0)->whereIn('status',[2,3,4,5])->orderBy('created_time')->get();
        foreach($in_progress_tasks as $task)
        {
            
            $task_array[]   =   array(
                        'task_id'       =>$task['id'],
                        'name'          =>$task['name'],
                        'description'   =>  $task['description'],
                        'project_name'  =>  @$task->proj_name->name,
                        'user_name'     =>$task->user->name,
                        'created_by'    =>  $task->user->name,
                        'assign_by'     =>$task->user->name,
                        'created_time'  =>  $task['created_time'],
                        'dead_line'     =>  $task['dead_line'],
                        'priority'      =>  $task['priority'],
                        'assign_time'   =>  $task['assign_time'],
                        'start_time'    =>  $task['start_time'],
                        'closing_time'  =>  $task['closing_time'],
                        'estimated_time'=>  $task['estimated_time'],
                    );
        }
        $new_array=array('in_progress_tasks'=>$task_array);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    public function leave_req(Request $request)
    {
        $purpose= $request->purpose;
        $apply_to= 2;
        $from= $request->get('from',date('Y-m-d H:i:s'));
        $to= $request->get('to',date('Y-m-d H:i:s'));
        $description    =   $request->description;
        $approval    =   0;
        $created_at  =  date('Y-m-d H:i:s');
        $user_id    =   $request->user_id;
        DB::table('leave_req')->insert(array(
                    'purpose'=>$purpose,
                    'apply_to'=>$apply_to,
                    'from'=>$from,
                    'to'=>$to,
                    'description'=>$description,
                    'approval'=>$approval,
                    'created_at'=>$created_at,
                    'user_id'=>$user_id,
        ));
        $new_array=array('create_message'=>'Leave Request Approved');
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    
    public function get_leave_purposes(){
        $leave_type     =   DB::table('leave_type_head')->where('is_published','=',1)->get();
        foreach($leave_type as $leave)
        {
            $purposes[]  = array('id'=>$leave->id,'name'=>$leave->name);
        }
        
        $new_array=array('leave_purposes'=>$purposes);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    
    public function get_leave_requests()
    {
        $all   =    DB::table('leave_req')->where('approval','=',0)->get();
        foreach($all as $leave){
            $user= User::select('name')->where('id','=',$leave->user_id)->first();
            $purpose=DB::table('leave_type_head')->select('name')->where('id','=',$leave->purpose)->first();
            
            $from=$leave->from;
            $to=$leave->to;
            $description=$leave->description;
            $leave_array[]  = array(
                'id'=>$leave->id,
                'user'=>$user->name,
                'purpose'=>$purpose->name,
                'from'=>$from,
                'to'=>$to,
                'description'=>$description,
                'status'=>$leave->approval
            );
        }
        $new_array=array('leave_requests'=>$leave_array);
        return json_encode($new_array,JSON_PRETTY_PRINT);
    }
    
    public function leave_accept(Request $request)
    {
        $id         =   $request->id;
        $status     =   $request->status;
        if($status ==0)
        {
            DB::table('leave_req')->where('id','=',$id)->delete();
            $new_array=array('accept_message'=>'Leave Request Discarded');
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
        else
        {
            DB::table('leave_req')->where('id','=',$id)->update(array('approval'=>$status));
            $new_array=array('accept_message'=>'Leave Request Approved');
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
    }
    
        public function login(Request $request)
    {
        $email=$request->email;
        $password=$request->password;
        
        if(Auth::attempt(['email'=>$email,'password'=>$password]))
        {
            $user=Auth::user();
            $info=  array(
                    'login_message'=>'Successfully Logged In',
                    'user_id'=>$user->id,
                    'user_name'=>$user->name,
                    'email'=>$user->email,
                    'user_type'=>$user->utype
                );
            $new_array= array('login_info'=>$info);
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
        else
        {
            $info= array('login_message'=>'Email or Password Is Invalid. Try Again !');
            $new_array= array('login_info'=>$info);
            return json_encode($new_array,JSON_PRETTY_PRINT);
        }
    
    }
}
