<?php

namespace App\Models;

use CodeIgniter\Model;

class LeadModel extends Model
{
    protected $db;
    protected $session;

    public function __construct()
    {
        parent::__construct();
        $this->db      = \Config\Database::connect();
        $this->session = \Config\Services::session();
        $this->request = \Config\Services::request();
    }

    public function add_lead()
    {
        
        $user_id   = $this->session->get('user_id');
        $user_type = $this->session->get('user_type');
        if ($user_type == 1) {
            $assigned_to = $this->request->getPost('assigned_to');
        } else {
            $assigned_to = $this->request->getPost('user_id');
        }
        $row = [
            'user_id'          => $assigned_to,
            'name'             => ucwords(strtolower(trim($this->request->getPost('full_name')))),
            'phone'            => $this->request->getPost('mobile'),
            'email'            => $this->request->getPost('email'),
            'enquiry_for'      => $this->request->getPost('course'),
            'course'           => $this->request->getPost('course'),
            'state'            => $this->request->getPost('state'),
            'city'             => $this->request->getPost('city'),
            'lead_source'      => $this->request->getPost('lead_source'),
            'remarks'          => ucwords(strtolower($this->request->getPost('remarks'))),
            'created_at'       => date("Y-m-d H:i:s"),
            'ip_address'       => $_SERVER['REMOTE_ADDR'],
        ];
        
        $this->db->table('leads')->insert($row);
        $inserted_id = $this->db->insertID();
        
        return $inserted_id;
    }

    public function assign_lead($user_id)
    {
        
        $row     = [
            'user_id'      => $user_id,
            'name'         => ucwords(strtolower(trim($this->request->getPost('name')))),
            'phone'        => $this->request->getPost('mobile'),
            'email'        => $this->request->getPost('email'),
            'enquiry_for'  => $this->request->getPost('enquiry_for'),
            'state'        => $this->request->getPost('state'),
            'city'         => $this->request->getPost('city'),
            'remarks'      => ucwords(strtolower($this->request->getPost('comment'))),
            'lead_source'  => $this->request->getPost('lsrc'),
            'campaign_for' => $this->request->getPost('cfor'),
            'created_at'   => date("Y-m-d H:i:s"),
            'ip_address'   => $_SERVER['REMOTE_ADDR'],
        ];
        $this->db->table('leads')->insert($row);
        $inserted_id = $this->db->insertID();
        return $inserted_id;
    }

    public function update_lead($id)
    {
        
        $row     = [
            'name'         => ucwords(strtolower(trim($this->request->getPost('full_name')))),
            'phone'        => $this->request->getPost('mobile'),
            'email'        => $this->request->getPost('email'),
            'enquiry_for'  => $this->request->getPost('course'),
            'course'       => $this->request->getPost('course'),
            'state'        => $this->request->getPost('state'),
            'city'         => $this->request->getPost('city'),
            'lead_source'  => $this->request->getPost('lead_source'),
            'remarks'      => ucwords(strtolower($this->request->getPost('comment'))),
            'updated_at' => date("Y-m-d H:i:s"),
        ];
        $builder = $this->db->table('leads');
        $builder->where('id', $id);
        $builder->update($row);
        return $this->db->affectedRows();
    }

    public function get_all_leads()
    {
        $uri   = service('uri');
        $start = $uri->getSegment(3);
        if ($start) {
            $START = $start;
        } else {
            $START = '0';
        }
        $LIMIT      = 10;
        $mobile     = $this->request->getGet('mobile');
        $email      = $this->request->getGet('email');
        $course_id  = $this->request->getGet('course_id');
        $cid        = $this->request->getGet('user_id');
        $cdate_from = $this->request->getGet('cdate_from');
        $cdate_to   = $this->request->getGet('cdate_to');
        $page       = $this->request->getGet('page');
        $user_type  = session()->get('user_type');
        $user_id    = session()->get('user_id');
        $where      = 'status=\'1\' AND delete_status=\'0\'';
        if ($user_type == '0') {
            $center_id = get_sub_center_by_id($user_id, 'string');
            if (empty($center_id) === FALSE) {
                $where .= ' AND user_id IN(' . $center_id . ')';
            }
        }
        if ($user_type == '2') {
            $parent_id = $this->session->get('parent_id');
            $center_id = get_team_lead_center($parent_id, 'string');
            if (empty($center_id) === FALSE) {
                $where .= ' AND user_id IN(' . $center_id . ')';
            }
        }
        if (isset($mobile) && $mobile != '') {
            $where .= ' AND phone=' . $mobile . '';
        } else if (isset($email) && $email != '') {
            $where .= ' AND email=\'' . $email . '\'';
        } else {
            if (isset($course_id) && $course_id != '') {
                $where .= ' AND course=\'' . $course_id . '\'';
            }
            if (isset($cid) && $cid != '') {
                $where .= ' AND user_id=' . $cid . '';
            }
            if (isset($cdate_from) && $cdate_from != '') {
                $created_date = date('Y-m-d', strtotime($cdate_from));
                if ($cdate_to == $cdate_from) {
                    $where .= ' AND DATE(created_at) = date(\'' . $created_date . '\')';
                } else {
                    $where .= ' AND created_at >= date(\'' . $created_date . '\')';
                }
            }
            if ((isset($cdate_from) && $cdate_from != '') && (isset($cdate_to) && $cdate_to != '')) {
                if ($cdate_to > $cdate_from) {
                    $cdate_to = date('Y-m-d', strtotime($cdate_to));
                    $where   .= ' AND created_at <= date(\'' . $cdate_to . '\')';
                }
            }
        }
        $total_query = "SELECT COUNT(id) as total FROM leads WHERE $where";
        if (isset($page) && $page != '') {
            $LIMIT  = $page;
            $where .= ' ORDER BY id desc limit ' . $START . ',' . $LIMIT . '';
        } else {
            $where .= ' ORDER BY id desc limit ' . $START . ',' . $LIMIT . '';
        }
        $query    = "SELECT * FROM leads WHERE $where";
        
        $num_row  = $this->db->query($total_query);
        $num_rows = $num_row->getRowArray();
        $this->create_paging($page, $num_rows['total']);
        $query = $this->db->query($query);
        return $query->getResult();
    }

    public function create_paging($page, $row_count)
    {
        $uri = service('uri');
        if (empty($page) === TRUE) {
            $page = 10;
        }
        $controller = $uri->getSegment(1);
        $function   = $uri->getSegment(2);
        $config     = [
            'base_url'   => base_url() . $controller . '/' . $function,
            'per_page'   => $page,
            'first_link' => 'First',
            'last_link'  => 'Last',
            'attributes' => ['class' => 'page-link'],
            'total_rows' => $row_count,
        ];
        $this->assign_paging($config);
    }

    public function assign_paging($config)
    {
        $uri    = service('uri');
        $page   = [];
        $start  = (int) $uri->getSegment(3) + 1;
        $end    = ($uri->getSegment(3) == floor($config['total_rows'] / $config['per_page'])) ? $config['total_rows'] : (int) $uri->getSegment(3) + $config['per_page'];
        if (empty($config['total_rows']) === FALSE) {
            $page['showing_result'] = "Showing " . $start . " to " . $end . " of " . $config['total_rows'] . " Results";
        }
        $page['paging'] = '';
        $view           = \Config\Services::renderer();
        $view->setData($page);
    }

    public function delete_lead($id)
    {
        if ((isset($id) && $id != "")) {
            $row     = ['delete_status' => '1'];
            $builder = $this->db->table('leads');
            $builder->where('id', $id);
            $builder->update($row);
            return $this->db->affectedRows();
        } else {
            return false;
        }
    }

    public function get_lead_by_id($id)
    {
        $builder = $this->db->table('leads');
        $builder->where('id', $id);
        $builder->where('delete_status', '0');
        $query = $builder->get();
        return $query->getRowArray();
    }

    public function get_user_lead_by_id($user_id, $lead_id)
    {
        $builder = $this->db->table('leads');
        $builder->where('id', $lead_id);
        $builder->where('user_id', $user_id);
        $builder->where('delete_status', '0');
        $query = $builder->get();
        return $query->getRowArray();
    }

    public function check_today_assigned_lead($user_id)
    {
        $builder = $this->db->table('leads');
        $builder->select('user_id');
        $builder->select('count(id) as total_lead');
        $builder->whereIn('user_id', $user_id);
        $builder->where('delete_status', '0');
        $builder->groupBy('user_id');
        $query = $builder->get();
        return $query->getRowArray();
    }

    public function disposition_list($dtype = NULL)
    {
        $builder = $this->db->table('disposition');
        if (isset($dtype) && $dtype != '') {
            $builder->where('disposition_type', $dtype);
        }
        $builder->where('status', '1');
        $query = $builder->get();
        return $query->getResultArray();
    }

    public function get_disposition_by_id($id)
    {
        $builder = $this->db->table('disposition');
        $builder->where('status', '1');
        $builder->where('id', $id);
        $query = $builder->get();
        return $query->getRowArray();
    }

    public function add_activity()
    {
        
        $row     = [
            'lead_id'       => $this->request->getPost('lid'),
            'user_id'       => $this->session->get('user_id'),
            'activity_type' => $this->request->getPost('activity_type'),
            'opportunity'   => $this->request->getPost('opportunity'),
            'comments'      => $this->request->getPost('comment'),
            'created_by'    => $this->session->get('user_name'),
            'created_at'    => date("Y-m-d H:i:s"),
        ];
        $this->db->table('lead_activity')->insert($row);
        $inserted_id = $this->db->insertID();
        $this->update_follow_up($this->request->getPost('lid'), $this->request->getPost('follow_up'));
        return $inserted_id;
    }

    public function update_follow_up($id, $follow_up = NULL)
    {
        $lead_details = $this->get_lead_by_id($id);
        $row          = [];
        if ($lead_details['attempted'] == '0') {
            $row['attempted']      = '1';
            $row['attempted_date'] = date("Y-m-d H:i:s");
            $row['updated_at']     = date("Y-m-d H:i:s");
        }
        if (isset($follow_up) && $follow_up != '') {
            $row['follow_up']  = date("Y-m-d", strtotime($follow_up));
            $row['updated_at'] = date("Y-m-d H:i:s");
        }
        if (empty($row) === FALSE) {
            $builder = $this->db->table('leads');
            $builder->where('id', $id);
            $builder->update($row);
            return $this->db->affectedRows();
        }
    }

    public function lead_activity_by_id($lead_id)
    {
        $builder = $this->db->table('lead_activity');
        $builder->where('lead_id', $lead_id);
        $builder->orderBy('id', 'desc');
        $query = $builder->get();
        return $query->getResultArray();
    }

    public function sales_activity()
    {
        
        $row     = [
            'lead_id'      => $this->request->getPost('lid'),
            'user_id'      => $this->session->get('user_id'),
            'product'      => $this->request->getPost('product'),
            'sales_status' => $this->request->getPost('sales_status'),
            'university'   => $this->request->getPost('university'),
            'sales_date'   => date("Y-m-d", strtotime($this->request->getPost('sales_date'))),
            'created_by'   => $this->session->get('user_name'),
            'created_at'   => date("Y-m-d H:i:s"),
        ];
        $this->db->table('sales')->insert($row);
        $inserted_id = $this->db->insertID();
        $row         = [
            'lead_id'    => $this->request->getPost('lid'),
            'user_id'    => $this->session->get('user_id'),
            'comments'   => "Attempted Sales Activity status is " . $this->request->getPost('sales_status'),
            'created_by' => $this->session->get('user_name'),
            'created_at' => date("Y-m-d H:i:s"),
        ];
        $this->db->table('lead_activity')->insert($row);
        return $inserted_id;
    }

    public function add_task()
    {
      
        $row     = [
            'lead_id'       => $this->request->getPost('lid'),
            'user_id'       => $this->session->get('user_id'),
            'task_type'     => $this->request->getPost('task_type'),
            'schedule_date' => date("Y-m-d H:i:s", strtotime($this->request->getPost('schedule'))),
            'comments'      => $this->request->getPost('comment'),
            'created_by'    => $this->session->get('user_name'),
            'created_at'    => date("Y-m-d H:i:s"),
        ];
        $this->db->table('lead_task')->insert($row);
        $inserted_id = $this->db->insertID();
        $row         = [
            'lead_id'    => $this->request->getPost('lid'),
            'user_id'    => $this->session->get('user_id'),
            'comments'   => "Attempted Task Type :" . $this->request->getPost('task_type') . ' And Schedule Date : ' . $this->request->getPost('schedule'),
            'created_by' => $this->session->get('user_name'),
            'created_at' => date("Y-m-d H:i:s"),
        ];
        $this->db->table('lead_activity')->insert($row);
        return $inserted_id;
    }

    public function lead_task_by_user_id($user_id)
    {
        $builder = $this->db->table('lead_task');
        $builder->where('user_id', $user_id);
        $builder->where('schedule_date >=', date("Y-m-d"));
        $builder->orderBy('schedule_date', 'desc');
        $query = $builder->get();
        return $query->getResultArray();
    }

    public function get_lead_source_list()
    {
        $builder = $this->db->table('lead_source');
        $builder->where('status', '1');
        $query = $builder->get();
        return $query->getResultArray();
    }

    public function manage_leads()
    {
        $uri   = service('uri');
        $start = $uri->getSegment(3);
        if ($start) {
            $START = $start;
        } else {
            $START = '0';
        }
        $LIMIT      = 10;
        $lstage     = $this->request->getGet('lstage');
        $lsource    = $this->request->getGet('lsource');
        $cid        = $this->request->getGet('user_id');
        $cdate_from = $this->request->getGet('cdate_from');
        $cdate_to   = $this->request->getGet('cdate_to');
        $page       = $this->request->getGet('page');
        $drange     = $this->request->getGet('drange');
        $user_type  = $this->session->get('user_type');
        $user_id    = $this->session->get('user_id');
        $where      = 'status=\'1\' AND delete_status=\'0\'';
        if ($user_type == '0') {
            $center_id = get_sub_center_by_id($user_id, 'string');
            if (empty($center_id) === FALSE) {
                $where .= ' AND leads.user_id IN(' . $center_id . ')';
            }
        }
        if ($user_type == '2') {
            $parent_id = $this->session->get('parent_id');
            $center_id = get_team_lead_center($parent_id, 'string');
            if (empty($center_id) === FALSE) {
                $where .= ' AND leads.user_id IN(' . $center_id . ')';
            }
        }
        if (isset($lsource) && $lsource != '') {
            $where .= ' AND lead_source=\'' . $lsource . '\'';
        }
        if (isset($cid) && $cid != '') {
            $where .= ' AND leads.user_id=' . $cid . '';
        }
        if (isset($cdate_from) && $cdate_from != '') {
            $created_date = date('Y-m-d', strtotime($cdate_from));
            if ($cdate_to == $cdate_from) {
                $where .= ' AND DATE(leads.created_at) = date(\'' . $created_date . '\')';
            } else {
                $where .= ' AND leads.created_at >= date(\'' . $created_date . '\')';
            }
        }
        if ((isset($cdate_from) && $cdate_from != '') && (isset($cdate_to) && $cdate_to != '')) {
            if ($cdate_to > $cdate_from) {
                $cdate_to = date('Y-m-d', strtotime($cdate_to));
                $where   .= ' AND leads.created_at <= date(\'' . $cdate_to . '\')';
            }
        }
        $total_query = "SELECT COUNT(id) as total FROM leads WHERE $where";
        if (isset($page) && $page != '') {
            $LIMIT  = $page;
            $where .= ' ORDER BY id desc limit ' . $START . ',' . $LIMIT . '';
        } else {
            $where .= ' ORDER BY id desc limit ' . $START . ',' . $LIMIT . '';
        }
        $query    = "SELECT * FROM leads WHERE $where";
        $num_row  = $this->db->query($total_query);
        $num_rows = $num_row->getRowArray();
        $this->create_paging($page, $num_rows['total']);
        $query = $this->db->query($query);
        return $query->getResult();
    }

    public function update_lead_assignment($user_id, $ids)
    {
        $updated_by = $this->session->get('user_id');
        $row        = [
            'user_id'    => $user_id,
            'updated_by' => $updated_by,
            'updated_at' => date("Y-m-d H:i:s"),
        ];
        $builder = $this->db->table('leads');
        $builder->whereIn('id', explode(',', $ids));
        $builder->update($row);
        echo $ids;
        echo $this->db->getLastQuery();
        exit;
        return $this->db->affectedRows();
    }
}