<?php

namespace App\Controllers;

class Leads extends BaseController
{
    
    public function __construct()
    {
		if (!is_numeric(session()->get('user_type'))) {
            redirect()->to(base_url('login/index'))->send();
            exit;
        }
        $this->LeadModel   = new \App\Models\LeadModel();	
        $this->AdminModel = new \App\Models\AdminModel();
        $this->ScriptModel = new \App\Models\ScriptModel();
    }

    public function add_lead()
    {
        $data['active'] = "lead";      
        return view('header', $data) . view('add_lead', $data) . view('footer', $data);
    }

    public function process_add_lead()
    {
        $config = [
            ['field' => 'full_name', 'label' => 'Full Name',  'rules' => 'required'],
            ['field' => 'mobile',    'label' => 'Mobile No',  'rules' => 'required|min_length[10]|max_length[10]'],
            ['field' => 'email',     'label' => 'Email ID',   'rules' => 'trim|required|valid_email'],
            ['field' => 'course',    'label' => 'Course',     'rules' => 'required'],
            ['field' => 'state',     'label' => 'State',      'rules' => 'required'],
            ['field' => 'city',      'label' => 'City',       'rules' => 'required'],
        ];

        if (!$this->validate(array_column($config, 'rules', 'field'))) {
            $data['active'] = "lead";
            $data['validation'] = $this->validator;                     
            return view('header', $data) . view('add_lead', $data) . view('footer', $data);
        } else {
            $data['active'] = "lead";            
            $inserted_id = $this->LeadModel->add_lead();            
            if($inserted_id){
                session()->setFlashdata('success_message', 'Lead has been added Successfully!!');
            }else{
                session()->setFlashdata('error_message', 'Failed to add lead. Please try again!!');
            }            
            return redirect()->to(base_url('leads/add_lead_success'));
        }
    }

    public function add_lead_success()
    {
        $data['active'] = "lead";
        return view('header', $data) . view('add_lead_success', $data) . view('footer', $data);
    }

    public function view_leads()
    {
        $data['active'] = "lead";
        $data['lead_details'] = $this->LeadModel->get_all_leads();
        return view('header', $data) . view('all_leads', $data) . view('footer', $data);
    }

    public function delete_lead($id)
    {
        $data['active'] = "lead";
        $status = $this->LeadModel->delete_lead($id);
        return redirect()->to(base_url('leads/view_leads'));
    }

    public function edit_lead($id)
    {
        $data['active'] = "lead";
        $data['get_lead'] = $this->LeadModel->get_lead_by_id($id);
        return view('header', $data) . view('edit_lead', $data) . view('footer', $data);
    }

    public function process_edit_lead($id)
    {
        $config = [
            ['field' => 'full_name', 'label' => 'Full Name', 'rules' => 'required'],
            ['field' => 'mobile',    'label' => 'Mobile No', 'rules' => 'required|min_length[10]|max_length[10]'],
            ['field' => 'email',     'label' => 'Email ID',  'rules' => 'trim|required|valid_email'],
            ['field' => 'course',    'label' => 'Course',    'rules' => 'required'],
            ['field' => 'state',     'label' => 'State',     'rules' => 'required'],
            ['field' => 'city',      'label' => 'City',      'rules' => 'required'],
        ];

        if (!$this->validate(array_column($config, 'rules', 'field'))) {
            $data['active'] = "lead";
            return view('header', $data) . view('edit_lead', $data) . view('footer', $data);
        } else {
            $data['active'] = "lead";
            $result = $this->LeadModel->update_lead($id);
            if ($result) {
                return redirect()->to(base_url('leads/view_leads'));
            }
        }
    }

    public function manage_leads()
    {
        $data['active'] = "lead";
        $data['lead_details'] = $this->LeadModel->manage_leads();
        return view('header', $data) . view('manage_leads', $data) . view('footer', $data);
    }

    public function lead_details($id)
    {
        $data['active'] = "lead";
        $data['lead_details'] = $this->LeadModel->get_lead_by_id($id);
        return view('header', $data) . view('view_leads', $data) . view('footer', $data);
    }

    public function add_activity()
    {
        $data['active'] = "lead";
        $config = [
            ['field' => 'activity_type', 'label' => 'Activity Type', 'rules' => 'required'],
        ];

        if (!$this->validate(array_column($config, 'rules', 'field'))) {
            $data['active'] = "lead";
            $data['status'] = "fail";
            $errors = $this->validator->getErrors();
            $data['activity_type'] = $errors['activity_type'] ?? '';
        } else {
            $data['active'] = "lead";
            $result = $this->LeadModel->add_activity();
            if ($result) {
                $data['status'] = "pass";
            }
        }
        echo json_encode($data);
    }

    public function activity()
    {
        $data['active'] = "lead";
        $user_type = session()->get('user_type');
        $user_id   = $this->request->getGet('user_id');
        $lead_id   = $this->request->getGet('lead_id');

        if ($user_type == '1') {
            $lead_details = $this->LeadModel->get_lead_by_id($lead_id);
        } else {
            $lead_details = $this->LeadModel->get_user_lead_by_id($user_id, $lead_id);
        }

        if (empty($lead_details) === FALSE) {
            $data = '<div class="modal fade show" id="kt_modal_4_2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="display: block; padding-right: 15px;" aria-modal="true">
                                        <div class="modal-dialog modal-xl" role="document">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalLabel">Add Activity</h5>
                                                    <button type="button" class="close" data-dismiss="modal" onClick="closeActivity();" aria-label="Close">
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                <form name="activity-form" id="activity-form">';
                                      $dispos = get_disposition();
                               $data .= ' <div class="form-group row">
                                        <label class="col-xl-2 col-lg-2 col-form-label">Activity Type
                                            <span class="required"> * </span>
                                        </label>
                                        <div class="col-lg-9 col-xl-9">                                             
                                            <select name="activity_type" id="activity_type" class="form-control input-height" required>
                                                  <option value="">Choose Activity Type</option>';
                                                  foreach($dispos as $value){ 
                                                    if($value['disposition_type']=='action'){
                                            $data .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
                                                } }     
                                            $data .= '</select> 
                                            <span class="help-block"> </span>
                                        </div>
                                    </div>
                                     <div class="form-group row">
                                        <label class="col-xl-2 col-lg-2 col-form-label">Opportunity
                                            <span class="required"> * </span>
                                        </label>
                                        <div class="col-lg-9 col-xl-9">                                             
                                            <select name="opportunity" id="opportunity" class="form-control input-height" required>
                                                  <option value="">Choose Opportunity</option>';
                                                  foreach($dispos as $value){ 
                                                    if($value['disposition_type']=='opportunity'){
                                            $data .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
                                                } }     
                                            $data .= '</select> 
                                            <span class="help-block"> </span>
                                        </div>
                                    </div>
									<div class="form-group row">
											<label class="col-xl-2 col-lg-2 col-form-label">Comment
											</label> <div class="col-lg-9 col-xl-9">  
											    <textarea class="form-control" id="commnet" name="comment"></textarea>
											    </div>
											</div>
											<div class="form-group row">
											<label class="col-xl-2 col-lg-2 col-form-label">Follow Up
											</label>
											<div class="col-lg-9 col-xl-9">                                             
												<input class="form-control input-height" size="16" name="follow_up" id="datepicker"  placeholder="Choose Date dd-mm-yyyy" type="text" value="" aria-invalid="false">
											</div>
										</div>
                                               <input type="hidden" name="lid" id="lid" value="'.$lead_id.'">  
                                             </div>
                                        <div class="modal-footer">                               
                                            <button type="button" class="btn btn-secondary" data-dismiss="modal" onClick="closeActivity();">Close</button>
                                            <button type="button" class="btn btn-primary" onClick="submitActivity();" id="submit-activity">Add Activity</button>
                                        </div>
                                        </form>
                                    </div>
                                </div>
                            </div>';
        }
        echo $data;
    }

    public function leadactivity()
    {
        
        $data['active'] = "lead";
        $lead_id = $this->request->getGet('lead_id');
        $lead_activity = $this->LeadModel->lead_activity_by_id($lead_id);
        $data = '<ul class="list-group card-list-group">';
        if (empty($lead_activity) === FALSE) {
            foreach ($lead_activity as $key => $value) {
                $lead_dis = get_disposition_by_id($value['activity_type']);
                if (empty($lead_dis) === FALSE) {
                    if(isset($value['opportunity']) && $value['opportunity'] != ''){
                        $lead_opportunity = get_disposition_by_id($value['opportunity']);
                    }
                    $data .= '<li class="list-group-item py-5">
                            <div class="media m-0">
                                <div class="media-object mr-4"> <img src="' . base_url() . '/assets/media/users/default.jpg" class="avatar brround avatar-md" alt="image" style="width: 42px;height: 42px;border-radius: 23px;"></div>
                                <div class="media-body d-block">
                                    <div class="media-heading">
                                        <small class="float-right text-muted">' . date('d-m-Y H:i:s', strtotime($value['created_at'])) . '</small> 
                                        <h5><strong>' . $value['created_by'] . '</strong></h5>
                                    </div>
                                    <div> <strong>Activity Type: </strong> ' . $lead_dis['name'] . '</div>';
                    $data .= '<div> <strong>Opportunity: </strong> ' . $lead_opportunity['name'] . '</div>';
                    $data .= '<div> <strong>Comments: </strong> ' . $value['comments'] . '</div>
                                </div>
                            </div>
                            </li>';
                }
                        
            }
        } else {
            $data .= '<li class="list-group-item py-5">
		               <div class="media m-0">
		                  <div class="media-body d-block">				                     
		                     No Activity Found.				                     
		                  </div>
		               </div>
		            </li>';
        }
        $data .= '</ul>';
        echo $data;
    }

    public function task()
    {
        $data['active'] = "lead";
        $user_type = session()->get('user_type');
        $user_id   = $this->request->getGet('user_id');
        $lead_id   = $this->request->getGet('lead_id');

        if ($user_type == '1') {
            $lead_details = $this->LeadModel->get_lead_by_id($lead_id);
        } else {
            $lead_details = $this->LeadModel->get_user_lead_by_id($user_id, $lead_id);
        }

        if (empty($lead_details) === FALSE) {
            $data = '<div class="modal fade show" id="kt_modal_4_2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="display: block; padding-right: 15px;" aria-modal="true">
                                        <div class="modal-dialog modal-xl" role="document">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalLabel">Add New Task Activity</h5>
                                                    <button type="button" class="close" data-dismiss="modal" onClick="closeActivity();" aria-label="Close">
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                <form name="activity-form" id="activity-form">';
                                      $dispos = array('Meeting','Follow-Up','Phone Call','Walk-In');
                               $data .= ' <div class="form-group row">
                                        <label class="col-xl-2 col-lg-2 col-form-label">Task Type
                                            <span class="required"> * </span>
                                        </label>
                                        <div class="col-lg-9 col-xl-9">                                             
                                            <select name="task_type" id="task_type" class="form-control input-height" required>
                                                  <option value="">Choose Task Type</option>';
                                                  foreach($dispos as $value){ 
                                            $data .= '<option value="'.$value.'">'.$value.'</option>';
                                                }      
                                            $data .= '</select> 
                                            <span class="help-block"> </span>
                                        </div>
                                    </div>
									<div class="form-group row">
									<label class="col-xl-2 col-lg-2 col-form-label">Comment
									</label> <div class="col-lg-9 col-xl-9">  
									    <textarea class="form-control" id="commnet" name="comment"></textarea>
									    </div>
									</div>
									<div class="form-group row">
									<label class="col-xl-2 col-lg-2 col-form-label">Schedule
									 <span class="required"> * </span></label>
									<div class="col-lg-9 col-xl-9">                                             
										<input class="form-control input-height" size="16" name="schedule" id="datepicker"  placeholder="Choose Date dd-mm-yyyy" type="text" value="" aria-invalid="false" required>
										 <span class="help-block"> </span>
									</div>
								</div>
                                               <input type="hidden" name="lid" id="lid" value="'.$lead_id.'">  
                                             </div>
                                        <div class="modal-footer">                               
                                            <button type="button" class="btn btn-secondary" data-dismiss="modal" onClick="closeActivity();">Close</button>
                                            <button type="button" class="btn btn-primary" onClick="submitTask();" id="submit-activity">Submit</button>
                                        </div>
                                        </form>
                                    </div>
                                </div>
                            </div>';
        }
        echo $data;
    }

    public function atask()
    {
        $data['active'] = "lead";
        $config = [
            ['field' => 'task_type', 'label' => 'Task Type',      'rules' => 'required'],
            ['field' => 'schedule',  'label' => 'Schedule Date',   'rules' => 'required'],
        ];

        if (!$this->validate(array_column($config, 'rules', 'field'))) {
            $data['active'] = "lead";
            $data['status'] = "fail";
            $errors = $this->validator->getErrors();
            $data['task_type'] = $errors['task_type'] ?? '';
            $data['schedule']  = $errors['schedule'] ?? '';
        } else {
            $data['active'] = "lead";
            $result = $this->LeadModel->add_task();
            if ($result) {
                $data['status'] = "pass";
            }
        }
        echo json_encode($data);
    }

    public function sales()
    {
        $data['active'] = "lead";
        $user_type = session()->get('user_type');
        $user_id   = $this->request->getGet('user_id');
        $lead_id   = $this->request->getGet('lead_id');

        if ($user_type == '1') {
            $lead_details = $this->LeadModel->get_lead_by_id($lead_id);
        } else {
            $lead_details = $this->LeadModel->get_user_lead_by_id($user_id, $lead_id);
        }

        if (empty($lead_details) === FALSE) {
            $data = '<div class="modal fade show" id="kt_modal_4_2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="display: block; padding-right: 15px;" aria-modal="true">
                                        <div class="modal-dialog modal-xl" role="document">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalLabel">New Sales Activity</h5>
                                                    <button type="button" class="close" data-dismiss="modal" onClick="closeActivity();" aria-label="Close">
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                <form name="activity-form" id="activity-form">';
                                      $dispos = array('Open','Admission Done','Registration Done','Lost');
                               $data .= ' <div class="form-group row">
                                        <label class="col-xl-2 col-lg-2 col-form-label">Status
                                            <span class="required"> * </span>
                                        </label>
                                        <div class="col-lg-9 col-xl-9">                                             
                                            <select name="sales_status" id="sales_status" class="form-control input-height" required>';
                                            foreach($dispos as $value){ 
                                            $data .= '<option value="'.$value.'">'.$value.'</option>';
                                                }      
                                            $data .= '</select> 
                                            <span class="help-block"> </span>
                                        </div>
                                    </div>';
                                    $data .= ' <div class="form-group row">
                                        <label class="col-xl-2 col-lg-2 col-form-label">Product
                                            <span class="required"> * </span>
                                        </label>
                                        <div class="col-lg-9 col-xl-9">                                             
                                            <select name="product" id="product" class="form-control input-height" required>
                                            <option value="">Choose Product</option>';
                                               $courses = get_courses();
                                               $selected ='';   
                                               foreach($courses as $value){ 
                                               	if($lead_details['course']==$value['name']){
                                               		$selected ='selected';
                                               	}
                                            $data .= '<option value="'.$value['name'].'" '.$selected.'>'.$value['name'].'</option>';
                                                } 
                                            $data .= '</select> 
                                            <span class="help-block"> </span>
                                        </div>
                                    </div>
                                     <div class="form-group row">
                                        <label class="col-xl-2 col-lg-2 col-form-label">University
                                            <span class="required"> * </span>
                                        </label>
                                        <div class="col-lg-9 col-xl-9">                                             
                                            <select name="university" id="university" class="form-control input-height" required>
                                            <option value="">Choose University</option>';
                                            $uni = array('JNU','Jagannath','JECRC','Chandigarh','NMIMS','Lingayas');
                                             foreach($uni as $value){ 
                                            $data .= '<option value="'.$value.'">'.$value.'</option>';
                                                }     
                                            $data .= '</select> 
                                            <span class="help-block"> </span>
                                        </div>
                                    </div>
									<div class="form-group row">
									<label class="col-xl-2 col-lg-2 col-form-label">Sales Date
									 <span class="required"> * </span></label>
									<div class="col-lg-9 col-xl-9">                                             
										<input class="form-control input-height" size="16" name="sales_date" id="datepicker"  placeholder="Choose Date dd-mm-yyyy" type="text" value="" aria-invalid="false" required>
										<span class="help-block"> </span>
									</div>
								</div>
                                               <input type="hidden" name="lid" id="lid" value="'.$lead_id.'">  
                                             </div>
                                        <div class="modal-footer">                               
                                            <button type="button" class="btn btn-secondary" data-dismiss="modal" onClick="closeActivity();">Close</button>
                                            <button type="button" class="btn btn-primary" onClick="submitSalesActivity();" id="submit-activity"> Submit</button>
                                        </div>
                                        </form>
                                    </div>
                                </div>
                            </div>';
        }
        echo $data;
    }

    public function sales_activity()
    {
        $data['active'] = "lead";
        $config = [
            ['field' => 'sales_status', 'label' => 'Sales Status', 'rules' => 'required'],
            ['field' => 'product',      'label' => 'Product',      'rules' => 'required'],
            ['field' => 'university',   'label' => 'University',   'rules' => 'required'],
            ['field' => 'sales_date',   'label' => 'Sales Date',   'rules' => 'required'],
        ];

        if (!$this->validate(array_column($config, 'rules', 'field'))) {
            $data['active'] = "lead";
            $data['status'] = "fail";
            $errors = $this->validator->getErrors();
            $data['sales_status'] = $errors['sales_status'] ?? '';
            $data['product']      = $errors['product'] ?? '';
            $data['university']   = $errors['university'] ?? '';
            $data['sales_date']   = $errors['sales_date'] ?? '';
        } else {
            $data['active'] = "lead";
            $result = $this->LeadModel->sales_activity();
            if ($result) {
                $data['status'] = "pass";
            }
        }
        echo json_encode($data);
    }

    public function leadtask()
    {
        $data['active'] = "lead";
        $user_type = session()->get('user_type');
        $user_id   = session()->get('user_id');

        if (isset($user_id) && $user_id != '') {
            $data['status'] = "pass";
            $task = $this->LeadModel->lead_task_by_user_id($user_id);
            if (empty($task) === FALSE) {
                $tdata = [];
                foreach ($task as $key => $value) {
                    $tdata[$key]['lead_id']   = $value['lead_id'];
                    $tdata[$key]['user_name'] = ucfirst(session()->get('name'));
                    $tdata[$key]['task_type'] = $value['task_type'];
                    $tdata[$key]['comments']  = $value['comments'];
                }
            }
        } else {
            $data['status'] = "fail";
        }
        $data['tdata'] = $tdata;
        echo json_encode($data);
    }

    public function upload_leads()
    {
        $data['active'] = "lead";
        return view('header', $data) . view('upload_lead', $data) . view('footer', $data);
    }

    public function process_upload_leads()
    {
        $file = $_FILES["upload_lead"]["tmp_name"];
        $file_open = fopen($file, "r");
        $i = 0;
        $j = 200;

        while (($csv = fgetcsv($file_open, 1000, ",")) !== false) {
            $i++;
            if ($i > 1) {
                if (isset($csv[0]) && $csv[0] != '') {
                    $user_details = $this->AdminModel->get_center_by_user($csv[0]);
                    $row = [
                        'user_id'        => $user_details['uid'],
                        'name'           => $csv[1],
                        'email'          => $csv[2],
                        'lead_origin'    => $csv[3],
                        'phone'          => $csv[4],
                        'lead_source'    => ucwords(strtolower($csv[6])),
                        'city'           => $csv[6],
                        'state'          => $csv[7],
                        'course'         => $csv[8],
                        'specialization' => $csv[9],
                        'university'     => $csv[10],
                        'created_by'     => session()->get('user_name'),
                        'created_at'     => date("Y-m-d H:i:s", strtotime($csv[9])),
                        'updated_at'     => date("Y-m-d H:i:s", strtotime($csv[10])),
                    ];
                }
                if (empty($user_details) === TRUE) {
                    $lead_details = $this->ScriptModel->get_lead_by_email($csv[2]);
                    if (empty($lead_details) === TRUE) {
                        $inserted_id = $this->ScriptModel->add_leads($row);
                    }
                }
            }
            if ($i % $j == 0) {
                sleep(5);
            }
        }

        if ($i > 1) {
            session()->setFlashdata('success_message', 'Lead has been uploaded Successfully!!');
            return redirect()->to(base_url('leads/upload_leads'));
        } else {
            session()->setFlashdata('success_message', 'Lead has been uploaded Successfully!!');
            return redirect()->to(base_url('leads/upload_leads'));
        }
    }

    public function assign_lead()
    {
        $config = [
            ['field' => 'assigned_to', 'label' => 'Assigned To', 'rules' => 'required'],
            ['field' => 'lead_ids',    'label' => 'Lead ids',    'rules' => 'required'],
        ];

        if (!$this->validate(array_column($config, 'rules', 'field'))) {
            $data['active'] = "lead";
            $data['status'] = "fail";
            $errors = $this->validator->getErrors();
            $data['assigned_to'] = $errors['assigned_to'] ?? '';
            $data['lead_ids']    = $errors['lead_ids'] ?? '';
        } else {
            $data['active'] = "lead";
            $result = $this->LeadModel->update_lead_assignment(
                $this->request->getPost('assigned_to'),
                $this->request->getPost('lead_ids')
            );
            if ($result) {
                $data['status'] = "pass";
            }
        }
        echo json_encode($data);
    }
}