<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Hash;
use App\Exports\UserExport;
use Maatwebsite\Excel\Facades\Excel;
use Carbon\Carbon;

use App\User;
use App\Jobs;
use App\Permissions;
use App\Modules;
use App\Updates;
use Auth;
use DB;
use Mail;
use Session;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    private $e;
    private $a;

    public function basic_email($name, $email)
    {
        $data = array('name' => $name);
        $this->e = $email;
        $this->a = $name;
        Mail::send('delay_mail', $data, function ($message) {
            $message->to($this->e, $this->a)->subject('Booking Delayed');
            $message->from('aumar@geneticconcepts.org', 'Landlord Cert');
        });
        // echo "Basic Email Sent. Check your inbox.";
    }

    public function calender_show()
    {
        $jobs = [];
        if (Auth::user()->role_id < 3) {
            $jobs = Jobs::select("heating_type", 'property_type', 'postal_code as title', DB::raw('CONCAT(booking_date, " ", booking_time) AS start'), 'job_status as backgroundColor', 'title as title1', 'fore_name as fname', 'final_notes as notes', 'postal_code', 'last_name as last', 'address', 'email', 'contact_no as no', 'date_of_birth', 'booking_time as install', 'survey_date as survey', 'booking_date as book', 'id', 'created_at as job_status', 'updated_at as url1', 'heating_type as icon', 'no_of_beds')->where('status', 1)
                ->get();
            // return dump($jobs);
        } else if (Auth::user()->role_id == 4) {
            $jobs = Jobs::select("heating_type", 'property_type', 'installer_note', 'postal_code as title', DB::raw('CONCAT(booking_date, " ", booking_time) AS start'), 'job_status as backgroundColor', 'title as title1', 'fore_name as fname', 'last_name as last', 'address', 'email', 'contact_no as no', 'date_of_birth', 'booking_time as install', 'survey_date as survey', 'booking_date as book', 'id', 'created_at as job_status', 'updated_at as url1', 'heating_type as icon', 'no_of_beds', 'final_notes as notes')->where('status', 1)
                ->where('installer_id', Auth::id())->whereIn('job_status', [2])->get();
        } else {
            $jobs = Jobs::select('property_type', 'postal_code as title', DB::raw('CONCAT(booking_date, " ", booking_time) AS start'), 'job_status as backgroundColor', 'title as title1', 'fore_name as fname', 'last_name as last', 'address', 'email', 'contact_no as no', 'date_of_birth', 'booking_time as install', 'survey_date as survey', 'booking_date as book', 'id', 'created_at as job_status', 'updated_at as url', 'heating_type as icon', 'no_of_beds', 'final_notes as notes')->where('status', 1)
                ->where('user_id', Auth::id())->whereIn('job_status', [2])->get();
        }

        foreach ($jobs as $job) {
            switch ($job->backgroundColor) {
                case 1:
                    $job->backgroundColor = "surveyed";
                    break;
                case 2:
                    $job->backgroundColor = "booked";
                    break;
                case 3:
                    $job->backgroundColor = "insulated";
                    break;
                case 4:
                    $job->backgroundColor = "submitted";
                    break;
                case 5:
                    $job->backgroundColor = "canceled";
                    break;
            }
            if ($job->icon == "GAS") {
                $job->icon = "fire";
            } else {
                $job->icon = "bolt";
            }
            if (Auth::user()->role_id == 3) {
                $url = route('pending_job', ['id' => $job->id, 'status' => $job->backgroundColor]);
                $job->url = $url;
            } else {
                $url = route('pending_job', ['id' => $job->id, 'status' => $job->backgroundColor]);
                $job->url1 = $url;
            }
            $job->job_status = $job->backgroundColor;
            $job->title .= " " . $job->backgroundColor;
            switch ($job->backgroundColor) {
                case "surveyed":
                    $job->backgroundColor = "gray";
                    $job->start = $job->survey;
                    break;
                case "booked":
                    $job->backgroundColor = "orange";
                    break;
                case "insulated":
                    $job->backgroundColor = "green";
                    break;
                case "submitted":
                    $job->backgroundColor = "blue !important";
                    break;
                case "canceled":
                    $job->backgroundColor = "red";
                    break;
            }
        }
        // dd($jobs);
        // return dump($jobs);
        return view('calender', compact('jobs'));
    }
    
            //Code by Qaisar
        public function calender2_show()
    {
        $jobs = [];
        if (Auth::user()->role_id < 3) {
            $jobs = Jobs::select("heating_type", 'property_type', 'postal_code as title', DB::raw('CONCAT(booking_date, " ", booking_time) AS start'), 'job_status as backgroundColor', 'title as title1', 'fore_name as fname', 'final_notes as notes', 'postal_code', 'last_name as last', 'address', 'email', 'contact_no as no', 'date_of_birth', 'booking_time as install', 'survey_date as survey', 'booking_date as book', 'id', 'created_at as job_status', 'updated_at as url1', 'heating_type as icon', 'no_of_beds')->where('status', 1)
                ->get();
            // return dump($jobs);
        } else if (Auth::user()->role_id == 4) {
            $jobs = Jobs::select("heating_type", 'property_type', 'installer_note', 'postal_code as title', DB::raw('CONCAT(booking_date, " ", booking_time) AS start'), 'job_status as backgroundColor', 'title as title1', 'fore_name as fname', 'last_name as last', 'address', 'email', 'contact_no as no', 'date_of_birth', 'booking_time as install', 'survey_date as survey', 'booking_date as book', 'id', 'created_at as job_status', 'updated_at as url1', 'heating_type as icon', 'no_of_beds', 'final_notes as notes')->where('status', 1)
                ->where('installer_id', Auth::id())->whereIn('job_status', [2])->get();
        } else {
            $jobs = Jobs::select('property_type', 'postal_code as title', DB::raw('CONCAT(booking_date, " ", booking_time) AS start'), 'job_status as backgroundColor', 'title as title1', 'fore_name as fname', 'last_name as last', 'address', 'email', 'contact_no as no', 'date_of_birth', 'booking_time as install', 'survey_date as survey', 'booking_date as book', 'id', 'created_at as job_status', 'updated_at as url', 'heating_type as icon', 'no_of_beds', 'final_notes as notes')->where('status', 1)
                ->where('user_id', Auth::id())->whereIn('job_status', [2])->get();
        }

        foreach ($jobs as $job) {
            switch ($job->backgroundColor) {
                case 1:
                    $job->backgroundColor = "surveyed";
                    break;
                case 2:
                    $job->backgroundColor = "booked";
                    break;
                case 3:
                    $job->backgroundColor = "insulated";
                    break;
                case 4:
                    $job->backgroundColor = "submitted";
                    break;
                case 5:
                    $job->backgroundColor = "canceled";
                    break;
            }
            if ($job->icon == "GAS") {
                $job->icon = "fire";
            } else {
                $job->icon = "bolt";
            }
            if (Auth::user()->role_id == 3) {
                $url = route('pending_job', ['id' => $job->id, 'status' => $job->backgroundColor]);
                $job->url = $url;
            } else {
                $url = route('pending_job', ['id' => $job->id, 'status' => $job->backgroundColor]);
                $job->url1 = $url;
            }
            $job->job_status = $job->backgroundColor;
            $job->title .= " " . $job->backgroundColor;
            switch ($job->backgroundColor) {
                case "surveyed":
                    $job->backgroundColor = "gray";
                    $job->start = $job->survey;
                    break;
                case "booked":
                    $job->backgroundColor = "orange";
                    break;
                case "insulated":
                    $job->backgroundColor = "green";
                    break;
                case "submitted":
                    $job->backgroundColor = "blue !important";
                    break;
                case "canceled":
                    $job->backgroundColor = "red";
                    break;
            }
        }
        // dd($jobs);
        // return dump($jobs);
        return view('calender', compact('jobs'));
    }
    
    public function values($sd, $ed)
    {
        $result = array();
        if (Auth::user()->role_id < 3) {
            $total = count(Jobs::whereBetween('updated_at', array($sd, $ed))->where('status', 1)->get());
            $added = count(Jobs::whereBetween('survey_date', array($sd, $ed))->where('job_status', 1)->where('status', 1)->get());
            $booked = count(Jobs::whereBetween('booking_date', array($sd, $ed))->where('job_status', 2)->where('status', 1)->get());
            $insulated = count(Jobs::whereBetween('insulation_date', array($sd, $ed))->where('job_status', 3)->where('status', 1)->get());
            $submitted = count(Jobs::whereBetween('submit_date', array($sd, $ed))->where('job_status', 4)->where('status', 1)->get());
        } else {
            $total = count(Jobs::whereBetween('updated_at', array($sd, $ed))->where('status', 1)->where('user_id', Auth::id())->get());
            $added = count(Jobs::whereBetween('survey_date', array($sd, $ed))->where('job_status', 1)->where('user_id', Auth::id())->where('status', 1)->get());
            $booked = count(Jobs::whereBetween('booking_date', array($sd, $ed))->where('job_status', 2)->where('user_id', Auth::id())->where('status', 1)->get());
            $insulated = count(Jobs::whereBetween('insulation_date', array($sd, $ed))->where('job_status', 3)->where('user_id', Auth::id())->where('status', 1)->get());
            $submitted = count(Jobs::whereBetween('submit_date', array($sd, $ed))->where('job_status', 4)->where('user_id', Auth::id())->where('status', 1)->get());
        }

        array_push($result, $total, $added, $booked, $insulated, $submitted);
        return $result;
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {

        if (Session::get('Dashboard') == NULL) {
            $permissions = DB::table('permissions')
                ->select('modules.module as module', 'modules.id as id')
                ->join('modules', 'permissions.module_id', 'modules.id')
                ->where('permissions.user_id', Auth::id())
                ->get();
            foreach ($permissions as $permission) {
                Session::put($permission->module, $permission->id);
            }
        }
        // Stats of jobs
        $now = new Carbon();
        $today = $now->today()->format('Y-m-d');
        $sevendaysago = $now->today()->subDays(7);
        $tomorrow = $now->tomorrow()->format('Y-m-d');
        $start_of_this_week = $now->startOfWeek()->format('Y-m-d ');
        $end_of_this_week = $now->endOfWeek()->format('Y-m-d');
        $start_of_this_month = $now->startOfMonth()->format('Y-m-d');
        $end_of_this_month = $now->endOfMonth()->format('Y-m-d');
        $start_of_this_year = $now->startOfYear()->format('Y-m-d');
        $end_of_this_year = $now->endOfYear()->format('Y-m-d');
        // For Last Week
        $start_of_last_week = Carbon::now()->subWeek()->startOfWeek()->format('Y-m-d');
        $end_of_last_week = Carbon::now()->subWeek()->endOfWeek()->format('Y-m-d');

        $day = $this->values($today, $tomorrow);
        $week = $this->values($start_of_this_week, $end_of_this_week);
        $last_week = $this->values($start_of_last_week, $end_of_last_week);
        $month = $this->values($start_of_this_month, $end_of_this_month);
        $year = $this->values($start_of_this_year, $end_of_this_year);

        $result = array();
        array_push($result, $day, $week, $month, $year, $last_week);


        // return dump($result);
        // latest Updates
        $updates = DB::table('updates')
            ->select('updates.*', 'users.name')
            ->join('users', 'users.id', 'updates.user_id')
            ->latest()
            ->get();
        // Query for user attentions
        $jobs2 = Jobs::select('fore_name', 'last_name', 'contact_no', 'final_notes as notes', 'postal_code as code', 'address as add', 'booking_date as date', 'id', 'job_status')->where('job_status', 2)->where('booking_date', '<', $today)->where('status', 1)->get();
        $jobs3 = Jobs::select('fore_name', 'last_name', 'contact_no', 'final_notes as notes', 'postal_code as code', 'address as add', 'survey_date as date', 'id', 'job_status')->where('job_status', 1)->where('status', 1)->get();
        foreach ($jobs2 as $j) {
            $j->job_status = "booked";
        }

        foreach ($jobs3 as $j) {
            $j->job_status = "surveyed";
        }
        // return dump($result);
        if (Auth::user()->role_id < 3) {
            $jobs = Jobs::select('postal_code as title', 'updated_at as start', 'job_status as backgroundColor', 'title as title1', 'fore_name as fname', 'last_name as last', 'address', 'email', 'contact_no as no', 'date_of_birth', 'booking_time as install', 'survey_date as survey', 'booking_date as book')
                ->get();
        } else {
            $jobs = Jobs::select('postal_code as title', 'updated_at as start', 'job_status as backgroundColor', 'title as title1', 'fore_name as fname', 'last_name as last', 'address', 'email', 'contact_no as no', 'date_of_birth', 'booking_time as install', 'survey_date as survey', 'booking_date as book')
                ->where('user_id', Auth::id())->where('job_status', 2)->get();
        }

        foreach ($jobs as $job) {
            switch ($job->backgroundColor) {
                case 1:
                    $job->backgroundColor = "gray";
                    break;
                case 2:
                    $job->backgroundColor = "orange";
                    break;
                case 3:
                    $job->backgroundColor = "green";
                    break;
                case 4:
                    $job->backgroundColor = "blue !important";
                    break;
                case 5:
                    $job->backgroundColor = "red ";
                    break;
            }
        }

        $delay_booked = Jobs::select('id', 'title', 'fore_name', 'email')
            ->where('delay_mail', 0)
            ->where('user_id', Auth::id())
            ->where('status', 1)
            ->where('job_status', 2)
            ->where('booking_date', '<', $today)
            ->get();

        foreach ($delay_booked as $delayed) {
            // $admins=User::whereIn('role_id',[1,2])->get();

            // //Mail to admins and owner
            // foreach($admins as $admin)
            // {
            // $this->basic_email($admin->name,$admin->email);
            // }
            // $this->basic_email($delayed->fore_name,$delayed->email);
            Session::put('delayed', $delayed->title);
            $table = Jobs::findorfail($delayed->id);
            $table->delay_mail = 1;
            $table->save();
        }
        // $this->basic_email();
        // dump($start_of_this_week);
        // return dump($delay_booked);
        // return dump($result);
        $count = 0;
        return view('home', compact('updates', 'result', 'jobs', 'jobs2', 'jobs3', 'count'));
    }
    public function export($jobs_id)
    {

        $data = explode(',', $jobs_id);



        /* if (Auth::id() > 2) {
            $jobs = DB::table('jobs')->whereIn('id', $data)->get();
        } else {
            $jobs = DB::table('jobs')
                ->select('jobs.*', 'users.name as sales_by')->whereIn('jobs.id', $data)
                ->join('users', 'users.id', 'jobs.user_id')
                ->get();
        }
        
        return view('jobs.excel', compact('jobs')); */
        return Excel::download(new UserExport($data), 'jobs.xlsx');
    }

    public function addupdates(Request $request)
    {
        $update = new Updates();
        $update->text = $request->text;
        $update->user_id = Auth::id();
        $update->save();
        // return dump(Auth::id());
        return redirect()->back();
    }

    public function permissions()
    {
        $permissions = DB::table('permissions')
            ->select('permissions.*', 'modules.module')
            ->join('modules', 'permissions.module_id', 'modules.id')
            ->get();
        $users = User::where('status', '1')->get();
        // return dump($permissions);
        return view('permissions', compact('users', 'permissions'));
    }
    public function permissionsupdate(Request $request)
    {
        $user = (int) $request->user;
        $permissions = $request->perm;

        Permissions::where('user_id', $user)->delete();

        foreach ($permissions as $permission) {
            $table = new Permissions();
            $table->user_id = $user;
            $table->module_id = (int) $permission;
            $table->created_by = Auth::id();
            $table->save();
        }
        return redirect()->back();
    }


    //Users
    public function newuser(Request $request)
    {
        $emails = User::select('email')->get();
        return view('adduser', compact('emails'));
    }
    public function storeuser(Request $request)
    {
        $table = new User();
        $table->name = $request->forename;
        $table->last_name = $request->lastname;
        $table->email = $request->email;
        $table->address = $request->address;
        $table->phone = $request->contact_no;
        $table->password = Hash::make("11223344");
        $table->role_id = $request->role;
        $table->save();
        return redirect()->back();
    }


    public function profile()
    {
        return view('profile');
    }


    public function updateprofile(Request $request)
    {
        // return dump($request->hasFile('img'));
        $filename = Auth::user()->img;
        if ($request->hasFile('img')) {
            $file = $request->file('img');
            $filename = $file->getClientOriginalName();
            $file->move(public_path("/dist/img/"), $filename);
        }

        $table = User::findorfail(Auth::id());
        $table->name = $request->name;
        $table->last_name = $request->last_name;
        $table->phone = $request->phone;
        $table->address = $request->address;
        $table->img = $filename;
        if ($request->password != null) {
            $table->password = Hash::make($request->password);
        }
        $table->save();
        return redirect()->route('logout');
    }
}
