<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\CompanyModel;
use App\Models\Remarks;
use App\Models\FileUpload;
use App\Models\CompanyActivity;
use App\Models\ServiceList;
use App\Models\CompanyService;
use App\Models\ServiceAttachment;
use App\Models\Invoice;
use App\Models\AddressBookModel;
use Mail;
use File;
use App\User;
use DB;
class CompanyController extends Controller
{
    
    public function index(Request $req)
    {
        $data['cname']='';

        $data['services']=ServiceList::orderBy('name','asc')->get();

        $query=(new CompanyModel)->newQuery();

        if($req->has('cname'))
        {
            $cname=$req->get('cname');
            $data['cname']=$cname;
            if(!empty($cname))
            {
                $query->where('name','like',"%{$cname}%");
            }
        }
    
        $data['all'] = $query->with(['mtask'])->orderBy('name')->paginate(10);

        $data['title'] = "Companies";
        return view('admin.companies',$data);
    }

    function change_status(Request $req)
    {
        $id=$req->get('id');
        $status=$req->get('status');

        $company=CompanyModel::find($id);
        $company->status=$status;
        $company->save();

        return json_encode(['ok'=>true]);
    }
    
    public function create()
    {
        //
    }

   
    public function store(Request $request)
    {
        $name = $request->name;
        $industry = $request->industry;
        $service_required = $request->service_required;
        $current_condition = $request->current_condition;
        $mob1 = $request->mob1;
        $mob2 = $request->mob2;
        $email1 = $request->email1;
        $email2 = $request->email2;
        $web = $request->web;
        $details = $request->details;
        $address = $request->address;
        $remarks = $request->remarks;
        $display = $request->display==1?1:0;

        if(!empty($name) && !empty($mob1) && !empty($email1)){
            $sav = new CompanyModel;
            $sav->name = $name;
            $sav->industry = $industry;
            $sav->service_required = $service_required;
            $sav->current_condition = $current_condition;
            $sav->mob1 = $mob1;
            $sav->mob2 = $mob2;
            $sav->email1 = $email1;
            $sav->email2 = $email2;
            $sav->web = $web;
            $sav->details = $details;
            $sav->address = $address;
            $sav->remarks = $remarks;
            $sav->display = $display;
            $sav->save();
        }

        return redirect()->back()->with('msg', 'Data added successfully!');
    }

    
    public function show($id) // show is using as destroy :(
    {
        CompanyModel::find($id)->delete();
        return redirect()->back();
    }


    function get_service($id)
    {
        $data['service']=CompanyService::with(['services','company'])->where('id',$id)->first();
        $company_id=$data['service']->company_id;
        $data['company'] = CompanyModel::where('display',1)->get();
        $data['company_services']=CompanyService::with(['services','attachments'])->where('company_id',$company_id)->get();
        $data['filess'] = FileUpload::all();
        $data['services']=ServiceList::orderBy('name','asc')->get();
        $data['all'] = CompanyModel::with('contact_persons')->find($company_id);

        $data['title'] = "Service Details";
        return view('admin.company_info.service_details',$data);
    }

    function file_upload_view($id)
    {
        $data['service']=CompanyService::with(['services'])->find($id);
        return view('admin.company_info.service_docs_upload',$data);
    }

    function save_upload(Request $req)
    {
        $this->validate($req,[
            'file' => 'required|max:10000'
        ]);
        $service_id=$req->get('hdn_service_id');
        $title=$req->get('title');
        $file_name = time().'.'.$req->file('file')->getClientOriginalExtension();

        $req->file('file')->move(
              base_path() . '/assets/uploads/service/', $file_name
          );

        $att=new ServiceAttachment();
        $att->service_id=$service_id;
        $att->title=$title;
        $att->file_name=$file_name;
        $att->save();
        return redirect()->back()->with('msg','File uploaded successfully !!');
        //return redirect('admin/view_company/'.$req->get('hdn_com_id'))->with('msg','File uploaded successfully !!');
    }

    /**
     * assign service to company
     * @param  Request $req
     * @return json      
     */
    function assign_service(Request $req)
    {
        $com_id=$req->get('com_id');
        $service=$req->get('service');
        $contact_person=$req->get('contact_person');
        $contact_number=$req->get('contact_number');
        $deployement_unit=$req->get('deployement_unit');
        $po_details=$req->get('po_details');
        $renewal_cycle=$req->get('renewal_cycle');
        $free_session=$req->get('free_session');
        $start_date=$req->get('start_date');

        $com_service=new CompanyService();

        $com_service->service_id=$service;
        $com_service->company_id=$com_id;
        $com_service->contact_person=$contact_person;
        $com_service->contact_number=$contact_number;
        $com_service->deployment_unit_details=$deployement_unit;
        $com_service->po_details=$po_details;
        $com_service->renewal_cycle=$renewal_cycle;
        $com_service->free_session=$free_session;
        $com_service->start_date=$start_date;

        $com_service->save();
        $this->log_activity($com_id,'New service assigned !');
        return json_encode(['ok'=>true,'msg'=>'Service assigned to this company successfully !']);
    }

   
    public function edit($id)
    {
        $val = CompanyModel::find($id);
        $data['id'] = $id;
        $data['name'] = $val->name;
        $data['industry'] = $val->industry;
        $data['service_required'] = $val->service_required;
        $data['current_condition'] = $val->current_condition;
        $data['mob1'] = $val->mob1;
        $data['mob2'] = $val->mob2;
        $data['email1'] = $val->email1;
        $data['email2'] = $val->email2;
        $data['web'] = $val->web;
        $data['details'] = $val->details;
        $data['address'] = $val->address;
        $data['remarks'] = $val->remarks;
        $data['display'] = $val->display;

        return $data;
    }

    
    public function update(Request $request, $id)
    {
        //
    }

    public function update_company(Request $request){

        $id = $request->id;
        $name = $request->name;
        $industry = $request->industry;
        $service_required = $request->service_required;
        $current_condition = $request->current_condition;
        $mob1 = $request->mob1;
        $mob2 = $request->mob2;
        $email1 = $request->email1;
        $email2 = $request->email2;
        $web = $request->web;
        $details = $request->details;
        $address = $request->address;
        $remarks = $request->remarks;
        $display = $request->display==1?1:0;

        if(!empty($name) && !empty($mob1) && !empty($email1)){
            $sav = CompanyModel::find($id);
            $sav->name = $name;
            $sav->industry = $industry;
            $sav->service_required = $service_required;
            $sav->current_condition = $current_condition;
            $sav->mob1 = $mob1;
            $sav->mob2 = $mob2;
            $sav->email1 = $email1;
            $sav->email2 = $email2;
            $sav->web = $web;
            $sav->details = $details;
            $sav->address = $address;
            $sav->remarks = $remarks;
            $sav->display = $display;
            $sav->save();
        }
        $this->log_activity($id,'Company information updated !');
        return redirect()->back()->with('msg', 'Data updated successfully!');
    }

    function edit_company_info($id)
    {
        $data['company']=CompanyModel::find($id);

        return view('admin.company_info.edit_company',$data);
    }

    public function change_company_info(Request $request){

        $id = $request->id;
        $name = $request->com_name;
        $industry = $request->industry;
        $service_required = $request->req_service;
        $current_condition = $request->current_condition;
        $mob1 = $request->mobile1;
        $mob2 = $request->mobile2;
        $email1 = $request->email1;
        $email2 = $request->email2;
        $web = $request->web;
        $details = $request->details;
        $address = $request->address;
        $remarks = $request->remark;
        $display = $request->display==1?1:0;

        if(!empty($name) && !empty($mob1) && !empty($email1))
        {
            $sav = CompanyModel::find($id);
            $sav->name = $name;
            $sav->industry = $industry;
            $sav->service_required = $service_required;
            $sav->current_condition = $current_condition;
            $sav->mob1 = $mob1;
            $sav->mob2 = $mob2;
            $sav->email1 = $email1;
            $sav->email2 = $email2;
            $sav->web = $web;
            $sav->details = $details;
            $sav->address = $address;
            $sav->remarks = $remarks;
            $sav->display = $display;
            $sav->save();
        }
        $this->log_activity($id,'Company information updated !');
        return redirect()->back()->with('msg', 'Data updated successfully!');
    }

   
    public function destroy($id)
    {
        
    }

    public function view_company($id){

        $data['title'] = "Company Details";
        $data['company'] = CompanyModel::where('display',1)->get();
        $data['company_services']=CompanyService::with(['services'])->where('company_id',$id)->get();
        $data['filess'] = FileUpload::all();
        $data['services']=ServiceList::orderBy('name','asc')->get();
        $data['all'] = CompanyModel::with('contact_persons')->find($id);

        $data['invoice'] = Invoice::with(['items','company'])->where('client_id',$id)->get();

        $data['cilents'] = User::where('company',$id)->get();
        $data['managers_all'] = User::where('utype',2)->get();
        $company = CompanyModel::find($id);
        $data['company_id'] = $id;
        //var_dump($company->account_manager);
        $data['manager'] = User::find($company->account_manager);

        return view('admin.company_info.indi_company',$data);
    }

    public function save_remarks(Request $req)
    {
        date_default_timezone_set("Asia/Dhaka");
        $id = $req->company_id;
        $company_service_id=$req->has('company_service_id')?$req->get('company_service_id'):0;
        $remarks = $req->remarks;
        $date = date("Y-m-d h:i");

        if($remarks != '0')
        {
            $sav = new Remarks;
            $sav->remarks = $remarks;
            $sav->company_id = $id;
            $sav->company_service_id=$company_service_id;
            $sav->date = $date;
            $sav->save();
        }

        $all=false;
        if($company_service_id==0)
        {
            $all = Remarks::with(['user'])->where('company_id',$id)->orderBy('id','DESC')->get();
        }
        else
        {
            $all = Remarks::with(['user'])->where('company_id',$id)->where('company_service_id',$company_service_id)->orderBy('id','DESC')->get();
        }
        

        $str = "";

        return $this->fetch_remarks($all,$str); //call function

        //return $str;
    }

    public function remove_remarks(Request $req)
    {
        $id = $req->id;
        $company_id = $req->company_id;

        Remarks::find($id)->delete();
        $this->log_activity($company_id,'remanrks deleted');
        $all = Remarks::where('company_id',$company_id)->orderBy('id','DESC')->get();

        $str = "";

        return $this->fetch_remarks($all,$str); //call function
            

        //return $str;
        
    }

    /**
     * log activity in company info
     * @param  integer $company_id
     * @param  string  $activity  
     * @return void            
     */
    function log_activity($company_id=0,$activity='')
    {
        date_default_timezone_set("Asia/Dhaka");
        $id = $company_id;
        $date = date("Y-m-d H:i:s");

        $sav = new CompanyActivity;
        $sav->activity = $activity;
        $sav->company_id = $company_id;
        $sav->date = $date;
        $sav->user_id=\Auth::user()->id;
        $sav->save();
    }


    public function save_activity(Request $req)
    {
        date_default_timezone_set("Asia/Dhaka");
        $id = $req->company_id;
        $val = $req->val;
        $date = date("Y-m-d h:i");

        if($val != '0')
        {
            $sav = new CompanyActivity;
            $sav->activity = $val;
            $sav->company_id = $id;
            $sav->date = $date;
            $sav->save();
        }

        $all = CompanyActivity::where('company_id',$id)->orderBy('id','DESC')->get();

        $str = "";

        return $this->fetch_activity($all,$str); //call function

        //return $str;
    }

    public function remove_activity(Request $req)
    {
        $id = $req->id;
        $company_id = $req->company_id;

        CompanyActivity::find($id)->delete();

        $all = CompanyActivity::where('company_id',$company_id)->orderBy('id','DESC')->get();

        $str = "";

        return $this->fetch_activity($all,$str); //call function
    }

    public function fetch_remarks($all,$str){

        if(count($all) > 0){
            $str .="<ul class='list-group'>";
            foreach($all as $info){
                $str .="<li class='list-group-item'>";
                    $str.="<div class='col-lg-11 col-md-11 col-sm-12 col-xs-10'>";
                    $str .="$info->remarks";
                    $user_name=$info->user?$info->user->name:'';
                    $str .="<p class='remarks-footer'><i class='fa fa-user'></i> {$user_name} &nbsp;&nbsp;&nbsp;  <i class='fa fa-clock-o'></i> &nbsp;".date("d-M-Y H:i", strtotime($info->date)).'</p>';
                    $str .="</div>";
                    $str.="<div class='col-lg-1 col-md-1 col-sm-12 col-xs-10'>";
                    $str.="<button style='color:red;' class='btn btn-xs remove-remarks' data-id='{$info->id}'><i class='fa fa-trash-o'></i></button>";
                    $str.="</div><div class='clearfix'></div>";
                $str.="</li>";
            }
            $str .="</ul>";
        }
        else{
            $str .="No remarks available ...";
        }

        return $str;
    }

    public function fetch_activity($all,$str){

        if(count($all) > 0){
            $str .="<table class='table'>";
            foreach($all as $info){
                $str .="<tr>";
                    $str .="<td>$info->activity</td>";
                    $str .="<td>".date("d-M-Y H:i", strtotime($info->date))."</td>";
                    $str .="<td><button style='color:red;' class='btn btn-xs remove-activity' data-id='{$info->id}'><i class='fa fa-trash-o'></i></button></td>";
                $str .="</tr>";
            }
            $str .="</table>";
        }
        else{
            $str .="No activity available ...";
        }

        return $str;
    }

    public function send_email_to_company(Request $req){

        $file_name = "";
        $email1 = $req->email1;
        $email2 = $req->email2;
        $attachment_id = $req->attachment_id;

        if($attachment_id > 0){
            $att = FileUpload::find($attachment_id);
            $file_name = $att->url;
        }

        $emailss[0] = $email1;
        if(!empty($email2))
        {
            $emailss[1] = $email2;
        }

        $subj = $req->subj;
        $data['email_body'] = $req->email_body;

        Mail::send('emails.email_to_company', $data, function ($message) use($subj,$emailss,$file_name){
            $message->from('m.revinr@gmail.com', 'Revinr Hr');

            if(File::exists('assets/document/files/'.$file_name) && !empty($file_name)){
                $message->attach("assets/document/files/$file_name");
            }
            
            $message->subject($subj);
            $message->to($emailss)->cc('helaldu@gmail.com');
        });

        if( count(Mail::failures()) > 0 ) 
        {
            return "error";
        } 
        else 
        {
            return "success";
        }

        //return "$email1 - $email2 - $subj - $email_body";
    }


    public function company_user($id){
        
        $company_address = AddressBookModel::find($id);
        $cp_id=$company_address->id;
        $name = $company_address->name;
        $email = $company_address->email1;
        $mob = $company_address->mob1;
        $address = 'N/A';
        $company = $company_address->company_id;
        $website = 'N/A';
        $user_type = 3;
        $defult_password='revinr123';
        $password = bcrypt($defult_password);
        $email_check = User::where('email',$email)->first();
        
        if (count($email_check) <=0) {
            $sav = new User;
            $sav->designation=  $company_address->designation;
            $sav->name = $name;
            $sav->email = $email;
            $sav->mob = $mob;
            $sav->address = $address;
            $sav->company = $company;
            $sav->website = $website;
            $sav->utype = $user_type;
            $sav->password = $password;
            $sav->active = 1;
            if($sav->save()){
                $data=[
                    'user_name'=>$name,
                    'password'=>$defult_password,
                ];
                $subject="Resgistration as User";
                DB::table('address_book')->where('id','=',$cp_id)->update(array('system_user'=>1));
                Mail::send('emails.register', $data, function ($message) use ($email ,$subject)
            {
                $message->from('m.revinr@gmail.com', 'Revinr Task Management');
                $message->to($email )->subject($subject);
            });
                return redirect()->back()->with('msg', 'User Created Successfully');
            } else {
                return redirect()->back()->with('msg', 'Something Went Wrong Please Try Again');
            }
        }
        else{
            return redirect()->back()->with('msg', 'Email Already Use.');
        }
        
        
    }

    public function company_manager(Request $req){
        $company = $req->company;
        $user = User::find($req->user_id);
        $email = $user->email;

        $data = CompanyModel::find($company);
        $data->account_manager = $req->user_id;
        if($data->update()){
            $res=[
                'user_name'=>$user->name,
                'company_name'=>$data->name,
                'contact'=>$data->mob1,
            ];
            $subject="Added as Account Manager";
            Mail::send('emails.account_manager', $res, function ($message) use ($email ,$subject)
            {
                $message->from('m.revinr@gmail.com', 'Revinr Task Management');
                $message->to($email )->subject($subject);
            });
            return "Manager Created Successfully";
        } else {
            return "Something Went Wrong Please Try Again !";
        }
        
    }
}
