<?php

namespace App\Http\Controllers\CRMAgency;

use App\Models\CRMLeadModel;
use App\Models\CRMTaskModel;
use App\Fun\Fun;
use App\User;
use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\DataTables;

class TaskAgentController extends Controller
{
    public function index()
    {
        //
    }

    public function create($lead_id)
    {
        $u_id = Auth::user()->id;
        $lead_name = CRMLeadModel::find($lead_id);
        $agent = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
            ->where(function ($q) use ($u_id) {
            if(Auth::user()->role != 'Administrator') {
                $q->where('id', $u_id);
                $q->orwhere('leader_id', $u_id);
            }
        })->pluck('name', 'id');
        return view('CRMAgent.task.create', compact('lead_name','agent'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [

            'lead_id' => 'required',
            'task_type' => 'required',
            'subject' => 'required',
            'admin_date' => 'required',
            'admin_hour' => 'required',
            'admin_minutes' => 'required',
            'admin_shift' => 'required',
        ]);
        $lead = CRMLeadModel::find($request->lead_id);
        $call_log = new CRMTaskModel();
        $call_log->lead_id = $request->lead_id;
        $call_log->agent_id = $request->agent_id;
        $call_log->task_type = $request->task_type;
        $call_log->call_duration = $request->call_duration;
        $call_log->subject = $request->subject;
        $call_log->where = $request->where;
        $call_log->date = date('Y-m-d', strtotime($request->admin_date));
        $call_log->hour = sprintf('%02d', $request->admin_hour);
        $call_log->minutes = sprintf('%02d', $request->admin_minutes);
        $call_log->shift = $request->admin_shift;
        $call_log->note = $request->admin_note;
        $call_log->save();
        if ($call_log->task_type == 'Appointment') {
            return redirect()->route('appointment-agency.index')->with('success', 'Appointment log create successfully...');
        }
        if ($call_log->task_type == 'Meeting') {
            return redirect()->route('meeting-agency.index')->with('success', 'Meeting create successfully...');
        }
        if ($call_log->task_type == 'Call_log') {
            return redirect()->route('call-log-agency.index')->with('success', 'Call log create successfully...');
        }


    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $task = CRMTaskModel::find($id);
        $lead_name = CRMLeadModel::find($task->lead_id);
        $u_id = Auth::user()->id;
        $agent = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
            ->where(function ($q) use ($u_id) {
            if(Auth::user()->role != 'Administrator') {
                $q->where('id', $u_id);
                $q->orwhere('leader_id', $u_id);
            }
        })->pluck('name', 'id');
        return view('CRMAgent.task.edit', compact('lead_name', 'task','agent'));
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'lead_id' => 'required',
            'task_type' => 'required',
            'subject' => 'required',
            'date' => 'required',
            'hour' => 'required',
            'minutes' => 'required',
            'shift' => 'required',
        ]);
        $call_log = CRMTaskModel::find($id);
        $call_log->lead_id = $request->lead_id;
        $call_log->agent_id = $request->agent_id;
        $call_log->task_type = $request->task_type;
        $call_log->call_duration = $request->call_duration;
        $call_log->subject = $request->subject;
        $call_log->where = $request->where;
        $call_log->date = date('Y-m-d', strtotime($request->date));
        $call_log->hour = sprintf('%02d', $request->hour);
        $call_log->minutes = sprintf('%02d', $request->minutes);
        $call_log->shift = $request->shift;
        $call_log->note = $request->note;
        $call_log->save();
        if ($call_log->task_type == 'Appointment') {
            return redirect()->route('appointment-agency.index')->with('success', 'Appointment update successfully...');
        }
        if ($call_log->task_type == 'Meeting') {
            return redirect()->route('meeting-agency.index')->with('success', 'Meeting update successfully...');
        }
        if ($call_log->task_type == 'Call_log') {
            return redirect()->route('call-log-agency.index')->with('success', 'Call log update successfully...');
        }
    }

    public function destroy($id)
    {
        //
    }

    public function task_report()
    {
        $u_id = Auth::user()->id;
        $agent = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
            ->where(function ($q) use ($u_id) {
            if (!Auth::user()->role == 'Administrator') {
                $q->where('id', $u_id);
                $q->orwhere('leader_id', $u_id);
            }
        })->pluck('name', 'id');
        return view('CRMAgent.report.task-report', compact('agent'));
    }

    public function datatable_task_report(Request $request)
    {
        $agent_s = isset($request->agent_id) ? $request->agent_id : '0';
        $status_s = isset($request->status) ? $request->status : '';
        $close_deal_s = isset($request->close_deal) ? $request->close_deal : '';

        $date_s = $request->date ? date('Y-m-d', strtotime($request->date)) : '0';
        $u_id = Auth::user()->id;
        $search = $request->input('search.value');
        $count_filter = CRMTaskModel::selectRaw('nso007_crm_task.convert_status')
            ->join('users', 'users.id', 'nso007_crm_task.agent_id')
            ->join('nso007_crm_leads', 'nso007_crm_leads.id', 'nso007_crm_task.lead_id')
            ->where('nso007_crm_task.delete_status', 0)
            ->where(function ($q) {
                if (Auth::user()->role != 'Administrator') {
                    $q->where('users.id', Auth::user()->id);
                    $q->orwhere('users.leader_id', Auth::user()->id);
                }
            })
            ->where(function ($q) use ($agent_s) {
                if ($agent_s != 0) {
                    $q->where('nso007_crm_task.agent_id', $agent_s);
                }
            })
            ->where(function ($q) use ($date_s) {
                if ($date_s != 0) {
                    $q->where('nso007_crm_task.date', $date_s);
                }
            })
            ->where(function($query) use ($search){
                $query->orWhere('nso007_crm_leads.name' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_crm_leads.family_name' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_crm_task.subject' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_crm_task.date' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_crm_task.hour' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_crm_task.note' , 'LIKE' , '%'.$search.'%');

            })
            ->count();
        $count_total = CRMTaskModel::selectRaw('nso007_crm_task.convert_status')
            ->join('users', 'users.id', 'nso007_crm_task.agent_id')
            ->join('nso007_crm_leads', 'nso007_crm_leads.id', 'nso007_crm_task.lead_id')
            ->where('nso007_crm_task.delete_status', 0)
            ->where(function ($q) {
                if (Auth::user()->role != 'Administrator') {
                    $q->where('users.id', Auth::user()->id);
                    $q->orwhere('users.leader_id', Auth::user()->id);
                }
            })
            ->count();
        $data = CRMTaskModel::selectRaw('nso007_crm_task.id as task_id,nso007_crm_task.date,CONCAT(user_firstname," ",user_lastname) AS agent_name,nso007_crm_task.lead_id,nso007_crm_task.convert_status,
            nso007_crm_task.subject,nso007_crm_task.hour,
            nso007_crm_task.minutes,nso007_crm_task.shift,nso007_crm_task.note,nso007_crm_task.complete_status,nso007_crm_task.convert_status,nso007_crm_task.task_type')
            ->join('users', 'users.id', 'nso007_crm_task.agent_id')
            ->where(function ($q) use ($u_id) {
                if (Auth::user()->role != 'Administrator') {
                    $q->where('users.id', $u_id);
                    $q->orwhere('users.leader_id', $u_id);
                }
            })
            ->where(function ($q) use ($agent_s) {
                if ($agent_s != 0) {
                    $q->where('nso007_crm_task.agent_id', $agent_s);
                }
            })
            ->where(function ($q) use ($status_s) {
                if ($status_s != '') {
                    $q->where('nso007_crm_task.complete_status', $status_s);
                }
            })
            ->where(function ($q) use ($close_deal_s) {

                if ($close_deal_s!='') {
                    if($close_deal_s==0){
                        $q->where('nso007_crm_task.convert_status', null);
                    }else{
                        $q->where('nso007_crm_task.convert_status', $close_deal_s);
                    }


                }
            })
            ->where(function ($q) use ($date_s) {
                if ($date_s != 0) {
                    $q->where('nso007_crm_task.date', $date_s);
                }
            })
            ->where('nso007_crm_task.delete_status', 0)->take(10);

        if ($request->isMethod('get')) {
            return DataTables::of($data)
                ->with([
                    "recordsTotal" => $count_total,
                    "recordsFiltered" => $count_filter,
                ])
                ->editColumn('date', function ($data) {
                    return date('d-m-Y', strtotime($data->date));
                })
                ->editColumn('hour', function ($task) {
                    return $task->hour . ':' . $task->minutes . ' ' . $task->shift;
                })
                ->editColumn('task_type', function ($task) {
                    return str_replace('_', ' ', $task->task_type);
                })
                ->addColumn('lead_name', function ($task) {
                    $lead = CRMLeadModel::find($task->lead_id);
                    return $lead->family_name . ' ' . $lead->name;
                })
                ->addColumn('contact', function ($task) {
                    $lead = CRMLeadModel::find($task->lead_id);
                    return $lead->contact;
                })
                ->editColumn('convert_status', function ($task) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $fail = 'បរាជ័យ';
                        $pending = 'រង់ចាំ';
                        $success = 'ជោគជ័យ';
                    } else {
                        $fail = 'Failed';
                        $pending = 'Pending';
                        $success = 'Successful';
                    }
                    return $task->convert_status == 1 ? '<span class="label label-success">' . $success . '</span>' : ($task->convert_status == 2 ? '<span class="label label-danger">' . $fail . '</span>' : '<span class="label label-warning">' . $pending . '</span>');
                })
                ->editColumn('complete_status', function ($task) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $pending = 'រង់ចាំ';
                        $complete = 'រួចរាល់';
                    } else {
                        $pending = 'Pending';
                        $complete = 'Complete';
                    }
                    return $task->complete_status == 1 ? '<span class="label label-primary">' . $complete . '</span>' : '<span class="label label-warning">' . $pending . '</span>';
                })
                ->addIndexColumn()
                ->rawColumns(['convert_status' => 'convert_status', 'complete_status' => 'complete_status', 'lead_name' => 'lead_name', 'contact' => 'contact'])
                ->make(true);
        }

    }

    public function view_task_report()
    {
        $agent_s = isset($_GET['agent_id']) ? $_GET['agent_id'] : '0';
        $status_s = isset($_GET['status']) ? $_GET['status'] : '';
        $close_deal_s = isset($_GET['close_deal']) ? $_GET['close_deal'] : '';
        $date_s = $_GET['date'] ? date('Y-m-d', strtotime($_GET['date'])) : '0';
        $u_id = Auth::user()->id;
        $data = CRMTaskModel::selectRaw('nso007_crm_task.id as task_id,nso007_crm_task.date,CONCAT(user_firstname," ",user_lastname) AS agent_name,nso007_crm_task.lead_id,
            nso007_crm_task.subject,nso007_crm_task.hour,
            nso007_crm_task.minutes,nso007_crm_task.shift,nso007_crm_task.note,nso007_crm_task.complete_status,nso007_crm_task.convert_status,nso007_crm_task.task_type')
            ->join('users', 'users.id', 'nso007_crm_task.agent_id')
            ->where(function ($q) use ($u_id) {
                $q->where('users.id', $u_id);
                $q->orwhere('users.leader_id', $u_id);
            })
            ->where(function ($q) use ($agent_s) {
                if ($agent_s != 0) {
                    $q->where('nso007_crm_task.agent_id', $agent_s);
                }
            })
            ->where(function ($q) use ($status_s) {
                if ($status_s != '') {
                    $q->where('nso007_crm_task.complete_status', $status_s);
                }
            })
            ->where(function ($q) use ($close_deal_s) {
                if ($close_deal_s != '') {
                    $q->where('nso007_crm_task.convert_status', $close_deal_s);
                }
            })
            ->where(function ($q) use ($date_s) {
                if ($date_s != 0) {
                    $q->where('nso007_crm_task.date', $date_s);
                }
            })
            ->where('nso007_crm_task.delete_status', 0)->get();
        return view('CRMAgent.report.show', compact('data'));
    }
}
