<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Proposals extends Admin_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('proposal_model');
        $this->load->library('gst');
    }

    private function normalize_proposal_date($date, $fallback = null)
    {
        $date = trim((string) $date);
        if ($date === '') {
            return $fallback ?: date('Y-m-d');
        }

        $formats = array('Y-m-d', 'Y.m.d', 'm.d.Y', 'd.m.Y', 'm-d-Y', 'd-m-Y', 'm/d/Y', 'd/m/Y');
        foreach ($formats as $format) {
            $parsed = DateTime::createFromFormat($format, $date);
            $errors = DateTime::getLastErrors();
            if ($parsed && ($errors === false || (empty($errors['warning_count']) && empty($errors['error_count'])))) {
                return $parsed->format('Y-m-d');
            }
        }

        $timestamp = safe_strtotime($date);
        return !empty($timestamp) ? date('Y-m-d', $timestamp) : ($fallback ?: date('Y-m-d'));
    }

    private function get_proposal_history_sidebar_payload($selected_id = 0)
    {
        $search = trim((string) $this->input->get('q', true));
        $page = (int) $this->input->get('page', true);
        $page = $page > 0 ? $page : 1;
        $per_page = 10;

        $total = (int) $this->proposal_model->count_proposal_sidebar($search);
        $pages = $total > 0 ? (int) ceil($total / $per_page) : 1;
        if ($page > $pages) {
            $page = $pages;
        }

        $offset = ($page - 1) * $per_page;

        return array(
            'sidebar_page' => $page,
            'sidebar_pages' => $pages,
            'sidebar_total' => $total,
            'sidebar_search' => $search,
            'sidebar_proposals' => $this->proposal_model->get_proposal_sidebar_page($per_page, $offset, $search),
            'sidebar_selected_proposal' => !empty($selected_id) ? $this->proposal_model->get_proposal_sidebar_proposal($selected_id) : null,
            'selected_proposal_id' => (int) $selected_id,
            'sidebar_base_path' => base_url('admin/proposals/index/proposals_history/'),
            'sidebar_page_url' => base_url('admin/proposals/index/proposals_history/' . (int) $selected_id),
        );
    }

    private function render_proposal_history_sidebar($selected_id = 0)
    {
        return $this->load->view('admin/proposals/_proposal_sidebar', $this->get_proposal_history_sidebar_payload($selected_id), true);
    }

    public function proposal_history_sidebar($selected_id = 0)
    {
        echo $this->render_proposal_history_sidebar($selected_id);
    }


    public function proposals_state_report()
    {
        if (!$this->input->is_ajax_request()) {
            redirect('admin/dashboard');
        }
        $data = array();
        $pathonor_jonno['proposals_state_report_div'] = $this->load->view("admin/proposals/proposals_state_report", $data, true);
        echo json_encode($pathonor_jonno);
        exit;
    }


    public function index($action = NULL, $id = NULL, $item_id = NULL)
    {

        $data['page'] = lang('sales');
        $data['sub_active'] = lang('proposals');
        $data['datatable'] = true;
        if (!empty($item_id)) {
            $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $id));
            if (!empty($can_edit)) {
                $data['item_info'] = $this->proposal_model->check_by(array('proposals_items_id' => $item_id), 'tbl_proposals_items');
            }
        }
        if ($action == 'edit_proposals') {
            $data['active'] = 2;
            $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $id));
            if (!empty($can_edit)) {
                $data['proposals_info'] = $this->proposal_model->check_by(array('proposals_id' => $id), 'tbl_proposals');
            }
        } else if ($action == 'client' || $action == 'leads') {
            $data['module_id'] = $id;
            $data['module'] = $action;
            $data['active'] = 2;
        } else {
            $data['active'] = 1;
        }
        // get all client
        $this->proposal_model->_table_name = 'tbl_client';
        $this->proposal_model->_order_by = 'client_id';
        $data['all_client'] = $this->proposal_model->get();
        // get permission user
        $data['permission_user'] = $this->proposal_model->all_permission_user('140');
        $type = $this->uri->segment(5);
        if (empty($type)) {
            $type = '_' . date('Y');
        }

        if (!empty($type) && !is_numeric($type)) {
            $filterBy = $type;
        } else {
            $filterBy = null;
        }


        if ($action == 'proposals_details') {
            redirect('admin/proposals/proposals_details/' . $id);
        } elseif ($action == 'proposals_history') {
            // get all proposals
            $data['proposals_info'] = $this->proposal_model->check_by(array('proposals_id' => $id), 'tbl_proposals');
            if (empty($data['proposals_info'])) {
                redirect('admin/proposals');
            }
            if ($data['proposals_info']->module == 'client') {
                $clientInfo = get_row('tbl_client', array('client_id' => $data['proposals_info']->module_id));
                if (!empty($clientInfo)) {
                    $data['proposals_info'] = (object) array_merge((array) $data['proposals_info'], (array) $clientInfo);
                }
            } elseif ($data['proposals_info']->module == 'leads') {
                $leadsInfo = get_row('tbl_leads', array('leads_id' => $data['proposals_info']->module_id));
                if (!empty($leadsInfo)) {
                    $data['proposals_info'] = (object) array_merge((array) $data['proposals_info'], (array) $leadsInfo);
                    $data['proposals_info']->name = $data['proposals_info']->lead_name;
                    $data['proposals_info']->zipcode = null;
                }
            }
            $data = array_merge($data, $this->get_proposal_history_sidebar_payload($id));
            $data['proposal_sidebar_html'] = $this->render_proposal_history_sidebar($id);
            $per_page = 20;
            $current_page = (int) $this->input->get('history_page', true);
            $current_page = $current_page > 0 ? $current_page : 1;
            $total_rows = $this->proposal_model->count_proposal_activities($id);
            $total_pages = max(1, (int) ceil($total_rows / $per_page));
            if ($current_page > $total_pages) {
                $current_page = $total_pages;
            }
            $offset = ($current_page - 1) * $per_page;
            $data['activities_info'] = $this->proposal_model->get_proposal_activity_page($id, $per_page, $offset);
            $data['history_page'] = $current_page;
            $data['history_pages'] = $total_pages;
            $data['history_total'] = $total_rows;
            $data['title'] = "proposals History"; //Page title
            $subview = 'proposals_history';
        } elseif ($action == 'email_proposals') {
            // get all proposals
            $data['all_proposals_info'] = $this->proposal_model->get_proposals($filterBy);
            $data['proposals_info'] = $this->proposal_model->check_by(array('proposals_id' => $id), 'tbl_proposals');
            $data['title'] = "Email proposals"; //Page title
            $subview = 'email_proposals';
        } elseif ($action == 'pdf_proposals') {
            return $this->proposals_details($id, true);
        } else {
            $data['title'] = lang('proposals'); //Page title
            $data['page_title'] = lang('proposals');
            $data['page_description'] = lang('proposal') . ' ' . lang('list');
            $proposalFilter = $this->proposal_model->get_invoice_filter();
            $status_filters = array();
            $period_filters = array();
            $year_filters = array();
            if (!empty($proposalFilter)) {
                foreach ($proposalFilter as $filter) {
                    $value = isset($filter['value']) ? $filter['value'] : '';
                    if (strpos($value, '_') === 0 && is_numeric(substr($value, 1))) {
                        $year_filters[] = $filter;
                    } elseif (in_array($value, array('last_month', 'this_months'), true)) {
                        $period_filters[] = $filter;
                    } else {
                        $status_filters[] = $filter;
                    }
                }
            }
            $data['header_actions'] = array();
            $data['header_actions_html'] = '';
            if ($this->session->userdata('user_type') == 1) {
                $proposal_quick_state_hidden = (config_item('proposal_state') == 'none');
                if ($proposal_quick_state_hidden) {
                    $title = lang('view_quick_state');
                    $url = 'show';
                    $icon = 'toggle-right';
                    $always_label = lang('quick_state') . ' ' . lang('always') . ': ' . lang('show');
                } else {
                    $title = lang('hide_quick_state');
                    $url = 'hide';
                    $icon = 'toggle-left';
                    $always_label = lang('quick_state') . ' ' . lang('always') . ': ' . lang('hide');
                }
                $data['header_actions_html'] .= ''
                    . '<button type="button" id="quick_state" data-default-hidden="' . ($proposal_quick_state_hidden ? '1' : '0') . '"'
                    . ' title="' . html_escape($title) . '" data-tooltip="' . html_escape($title) . '" data-placement="top" aria-label="' . html_escape($title) . '"'
                    . ' aria-controls="state_report" aria-expanded="' . ($proposal_quick_state_hidden ? 'false' : 'true') . '"'
                    . ' class="inline-flex h-11 w-11 items-center justify-center rounded-xl border border-border bg-white text-slate-700 shadow-sm transition hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800">'
                    . '<i data-lucide="' . ($proposal_quick_state_hidden ? 'panel-top-open' : 'panel-top-close') . '" class="h-4 w-4"></i>'
                    . '</button>';
                $data['header_actions_html'] .= ''
                    . '<a href="' . base_url('admin/dashboard/change_report/' . $url . '/proposal') . '"'
                    . ' data-no-instant-nav="1"'
                    . ' title="' . html_escape($always_label) . '" data-tooltip="' . html_escape($always_label) . '" data-placement="top" aria-label="' . html_escape($always_label) . '"'
                    . ' class="inline-flex h-11 w-11 items-center justify-center rounded-xl border border-amber-200 bg-amber-50 text-amber-700 shadow-sm transition hover:bg-amber-100 dark:border-amber-800/60 dark:bg-amber-900/30 dark:text-amber-300 dark:hover:bg-amber-900/40">'
                    . '<i data-lucide="' . html_escape($icon) . '" class="h-4 w-4"></i>'
                    . '</a>';
            }
            if (!empty(can_action('140', 'created')) || !empty(can_action('140', 'edited'))) {
                $data['header_actions'][] = array(
                    'label' => lang('create_proposal'),
                    'icon' => 'plus',
                    'href' => base_url('admin/proposals/createproposal'),
                    'style' => 'primary',
                );
            }
            $data['header_actions_html'] .= btn_modal(
                'admin/invoice/zipped/proposal',
                '<span>' . lang('zip_proposal') . '</span>',
                lang('zip_proposal'),
                'md',
                'archive',
                array(
                    'class' => 'inline-flex items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-2.5 text-sm font-semibold text-emerald-700 hover:bg-emerald-100 dark:border-emerald-800/60 dark:bg-emerald-900/30 dark:text-emerald-300 dark:hover:bg-emerald-900/40',
                )
            );

            $proposal_filter_items = array(
                array(
                    'label' => lang('all'),
                    'active' => true,
                    'attrs' => array(
                        'data-proposal-filter-action' => '1',
                        'data-proposal-filter' => '',
                        'data-proposal-search' => '',
                        'data-proposal-filter-label' => lang('all'),
                    ),
                ),
            );
            foreach ($status_filters as $filter) {
                $proposal_filter_items[] = array('label' => $filter['name'], 'attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-filter' => $filter['value'], 'data-proposal-search' => '', 'data-proposal-filter-label' => $filter['name']));
            }
            foreach ($period_filters as $index => $filter) {
                $proposal_filter_items[] = array('label' => $filter['name'], 'divider_before' => $index === 0, 'attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-filter' => $filter['value'], 'data-proposal-search' => '', 'data-proposal-filter-label' => $filter['name']));
            }
            if (!empty($year_filters)) {
                $proposal_filter_items[] = array('label' => lang('year'), 'icon' => 'calendar-range', 'divider_before' => true, 'items' => array_map(function ($filter) {
                    return array('label' => $filter['name'], 'attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-filter' => $filter['value'], 'data-proposal-search' => '', 'data-proposal-filter-label' => $filter['name']));
                }, $year_filters));
            }
            $proposal_filter_items[] = array('label' => lang('invoice'), 'icon' => 'file-text', 'divider_before' => true, 'items' => array(array('label' => lang('all') . ' ' . lang('invoice'), 'attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-filter' => '', 'data-proposal-search' => 'by_invoice', 'data-proposal-filter-label' => lang('all') . ' ' . lang('invoice')))), 'lookup' => array('endpoint' => base_url('admin/common/invoice_lookup'), 'limit' => 12, 'min_length' => 0, 'action_attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-search' => 'by_invoice'), 'filter_attr' => 'data-proposal-filter', 'label_attr' => 'data-proposal-filter-label', 'label_prefix' => lang('invoice') . ': ', 'placeholder' => lang('search') . ' ' . lang('invoice'), 'cache_key' => 'proposal_invoice_lookup'));
            $proposal_filter_items[] = array('label' => lang('estimate'), 'icon' => 'file-badge', 'items' => array(array('label' => lang('all') . ' ' . lang('estimate'), 'attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-filter' => '', 'data-proposal-search' => 'by_estimates', 'data-proposal-filter-label' => lang('all') . ' ' . lang('estimate')))), 'lookup' => array('endpoint' => base_url('admin/common/estimate_lookup'), 'limit' => 12, 'min_length' => 0, 'action_attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-search' => 'by_estimates'), 'filter_attr' => 'data-proposal-filter', 'label_attr' => 'data-proposal-filter-label', 'label_prefix' => lang('estimate') . ': ', 'placeholder' => lang('search') . ' ' . lang('estimate'), 'cache_key' => 'proposal_estimate_lookup'));
            $proposal_filter_items[] = array('label' => lang('sales') . ' ' . lang('agent'), 'icon' => 'user-check', 'items' => array(array('label' => lang('all') . ' ' . lang('sales') . ' ' . lang('agent'), 'attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-filter' => '', 'data-proposal-search' => 'by_agent', 'data-proposal-filter-label' => lang('all') . ' ' . lang('sales') . ' ' . lang('agent')))), 'lookup' => array('endpoint' => base_url('admin/common/staff_lookup'), 'limit' => 12, 'min_length' => 0, 'action_attrs' => array('data-proposal-filter-action' => '1', 'data-proposal-search' => 'by_agent'), 'filter_attr' => 'data-proposal-filter', 'label_attr' => 'data-proposal-filter-label', 'label_prefix' => lang('sales') . ' ' . lang('agent') . ': ', 'placeholder' => lang('search') . ' ' . lang('sales') . ' ' . lang('agent'), 'cache_key' => 'proposal_staff_lookup'));
            $data['header_filters'] = array(array('label' => 'Filters', 'icon' => 'sliders-horizontal', 'selected_label' => lang('all'), 'attrs' => array('id' => 'proposal-header-filter'), 'items' => $proposal_filter_items));
            $data['header_filter_extras_html'] = '';
            $subview = 'proposals';
        }
        $data['subview'] = $this->load->view('admin/proposals/' . $subview, $data, TRUE);
        $this->load->view('admin/_layout_main', $data); //page load
    }

    public function proposalsList($filterBy = null, $search_type = null)
    {
        if ($this->input->is_ajax_request()) {
            $search_by = $search_type;
            $edited = can_action('140', 'edited');
            $deleted = can_action('140', 'deleted');
            $this->load->model('datatables');
            $this->datatables->table = 'tbl_proposals';

            $custom_field = custom_form_table_search(11);
            $action_array = array('proposals_id');
            $main_column = array('reference_no', 'proposal_date', 'status', 'due_date', 'tags');
            $result = array_merge($main_column, $custom_field, $action_array);
            $this->datatables->column_order = $result;
            $this->datatables->column_search = $result;

            $this->datatables->order = array('proposals_id' => 'desc');

            if (!empty($edited) && !empty($deleted)) {
                if (empty($filterBy)) {
                    $filterBy = '_' . date('Y');
                }
            }
            if (!empty($filterBy) && !is_numeric($filterBy)) {
                $ex = explode('_', $filterBy);
                if ($ex[0] != 'c') {
                    $filterBy = $filterBy;
                }
            }
            $where = null;
            $where_in = null;
            if (!empty($search_by)) {
                if ($search_by == 'by_invoice') {
                    $where = array('convert' => 'Yes', 'convert_module' => 'invoice', 'convert_module_id' => $filterBy);
                }
                if ($search_by == 'by_agent') {
                    $where = array('user_id' => $filterBy);
                }
                if ($search_by == 'by_estimates') {
                    $where = array('convert' => 'Yes', 'convert_module' => 'estimate', 'convert_module_id' => $filterBy);
                }
            } else {
                if ($filterBy == 'last_month' || $filterBy == 'this_months') {
                    if ($filterBy == 'last_month') {
                        $month = date('Y-m', safe_strtotime('-1 months'));
                    } else {
                        $month = date('Y-m');
                    }
                    $where = array('proposal_month' => $month);
                } else if ($filterBy == 'expired') {
                    $where = array('UNIX_TIMESTAMP(due_date) <' => safe_strtotime(date('Y-m-d')));
                    $status = array('draft', 'pending');
                    $where_in = array('status', $status);
                } else if (strstr($filterBy, '_')) {
                    $year = str_replace('_', '', $filterBy);
                    $where = array('proposal_year' => $year);
                } else if (!empty($filterBy) && $filterBy != 'all') {
                    $where = array('status' => $filterBy);
                }
            }
            // get all invoice
            $fetch_data = $this->datatables->get_datatable_permission($where);

            $data = array();


            foreach ($fetch_data as $_key => $v_proposals) {
                if (!empty($v_proposals)) {
                    $action = null;
                    $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $v_proposals->proposals_id));
                    $can_delete = $this->proposal_model->can_action('tbl_proposals', 'delete', array('proposals_id' => $v_proposals->proposals_id));

                    if ($v_proposals->status == 'pending') {
                        $status_badge = "bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300";
                    } elseif ($v_proposals->status == 'accepted') {
                        $status_badge = "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300";
                    } elseif ($v_proposals->status == 'sent') {
                        $status_badge = "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300";
                    } else {
                        $status_badge = "bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300";
                    }

                    $sub_array = array();
                    $name = null;
                    $name .= '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/proposals/index/proposals_details/' . $v_proposals->proposals_id . '">' . $v_proposals->reference_no . '</a>';
                    if ($v_proposals->convert == 'Yes') {
                        if ($v_proposals->convert_module == 'invoice') {
                            $c_url = base_url() . 'admin/invoice/manage_invoice/invoice_details/' . $v_proposals->convert_module_id;
                            $text = lang('invoiced');
                        } else {
                            $text = lang('estimated');
                            $c_url = base_url() . 'admin/estimates/create/estimates_details/' . $v_proposals->convert_module_id;
                        }
                        if (!empty($c_url)) {
                            $name .= '<p class="text-sm m0 p0"><a class="text-success" href="' . $c_url . '">' . $text . '</a></p>';
                        }
                    }
                    $sub_array[] = $name;
                    $sub_array[] = display_date($v_proposals->proposal_date);
                    $overdue = '';
                    if ((safe_strtotime($v_proposals->due_date) < safe_strtotime(date('Y-m-d'))) && ($v_proposals->status == 'pending' || $v_proposals->status == 'draft')) {
                        $overdue = '<span class="ml-2 inline-flex items-center rounded-full bg-rose-100 px-2 py-0.5 text-xs font-semibold text-rose-700 dark:bg-rose-900/40 dark:text-rose-300">' . lang("expired") . '</span>';
                    }
                    $sub_array[] = '<span class="text-slate-700 dark:text-slate-200">' . display_date($v_proposals->due_date) . '</span>' . $overdue;

                    if ($v_proposals->module == 'client') {
                        $client_info = $this->proposal_model->check_by(array('client_id' => $v_proposals->module_id), 'tbl_client');
                        if (!empty($client_info)) {
                            $client_name = $client_info->name;
                        } else {
                            $client_name = '-';
                        }
                    } else if ($v_proposals->module == 'leads') {
                        $client_info = $this->proposal_model->check_by(array('leads_id' => $v_proposals->module_id), 'tbl_leads');
                        if (!empty($client_info)) {
                            $client_name = $client_info->lead_name;
                        } else {
                            $client_name = '-';
                        }
                    } else {
                        $client_name = '-';
                    }
                    $sub_array[] = html_escape($client_name);
                    $sub_array[] = display_money($this->proposal_model->proposal_calculation('total', $v_proposals->proposals_id), client_currency($v_proposals->module_id));
                    $sub_array[] = "<span class='inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold " . $status_badge . "'>" . lang($v_proposals->status) . "</span>";
                    $sub_array[] = get_tags($v_proposals->tags, true);

                    $custom_form_table = custom_form_table(11, $v_proposals->proposals_id);

                    if (!empty($custom_form_table)) {
                        foreach ($custom_form_table as $c_label => $v_fields) {
                            $sub_array[] = $v_fields;
                        }
                    }
                    $action .= '<div class="inline-flex flex-wrap items-center gap-0">';
                    if (!empty($can_edit) && !empty($edited)) {



						$action .= btn_modal('admin/proposals/clone_proposal/' . $v_proposals->proposals_id, '', lang('clone_project'), 'md', 'copy', ['class' => 'btn btn-success btn-xs h-7 mb-1 ',]);


                        $action .= btn_edit('admin/proposals/createproposal/edit_proposals/' . $v_proposals->proposals_id) . ' ';
                    }
                    if (!empty($can_delete) && !empty($deleted)) {


						$action .= ajax_anchor(base_url("admin/proposals/delete/delete_proposals/$v_proposals->proposals_id"), '', array("class" => "inline-flex h-7 items-center rounded-md border border-rose-200 bg-rose-50 px-2 py-1 text-xs font-semibold text-rose-700 hover:bg-rose-100 dark:border-rose-800 dark:bg-rose-900/20 dark:text-rose-300 dark:hover:bg-rose-900/40", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';

                    }
                    $change_status = null;
                    if (!empty($can_edit) && !empty($edited)) {
                        $ch_url = base_url() . 'admin/proposals/';
                        $change_status .= '<details class="relative inline-flex">
						<summary class="inline-flex cursor-pointer list-none items-center justify-center gap-1 rounded-md border border-slate-200 bg-white px-2 py-1 text-slate-500 shadow-sm transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-gray-200 ml-1 h-7 mb-1">
                    ' . lang('change') . '
            			</summary>
						<ul class="absolute right-0 top-full z-50 mt-1 min-w-[170px] overflow-hidden rounded-lg border border-slate-200 bg-white py-1 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-800">';
                        $change_status .= '<li><a class="block px-3 py-2 text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-gray-700" href="' . $ch_url . 'index/proposals_details/' . $v_proposals->proposals_id . '">' . lang('view_details') . '</a></li>';
                        $change_status .= '<li><a class="block px-3 py-2 text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-gray-700" href="' . $ch_url . 'index/email_proposals/' . $v_proposals->proposals_id . '">' . lang('send_email') . '</a></li>';
                        $change_status .= '<li><a class="block px-3 py-2 text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-gray-700" href="' . $ch_url . 'index/proposals_history/' . $v_proposals->proposals_id . '">' . lang('history') . '</a></li>';
                        if ($v_proposals->convert != 'Yes') {
                            $change_status .= '<li><a class="block px-3 py-2 text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-gray-700" href="#" data-modal-url="' . base_url('admin/proposals/convert_to/invoice/' . $v_proposals->proposals_id) . '" data-modal-title="' . html_escape(lang('convert_to_invoice')) . '" data-modal-size="xl">' . lang('convert') . ' ' . lang('to') . ' ' . lang('invoice') . '</a></li>';
                            $change_status .= '<li><a class="block px-3 py-2 text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-gray-700" href="#" data-modal-url="' . base_url('admin/proposals/convert_to/estimate/' . $v_proposals->proposals_id) . '" data-modal-title="' . html_escape(lang('convert_to_estimate')) . '" data-modal-size="xl">' . lang('convert') . ' ' . lang('to') . ' ' . lang('estimate') . '</a></li>';
                        }
                        $change_status .= '<li><a class="block px-3 py-2 text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-gray-700" href="' . $ch_url . 'change_status/declined/' . $v_proposals->proposals_id . '">' . lang('declined') . '</a></li>';
                        $change_status .= '<li><a class="block px-3 py-2 text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-gray-700" href="' . $ch_url . 'change_status/accepted/' . $v_proposals->proposals_id . '">' . lang('accepted') . '</a></li>';
                        $change_status .= '</ul></details>';
                        $action .= $change_status;
                    }
                    $action .= '</div>';
                    $sub_array[] = $action;
                    $data[] = $sub_array;
                }
            }
            render_table($data, $where, $where_in);
        } else {
            redirect('admin/dashboard');
        }
    }

    public function proposals_details($id, $pdf = null)
    {
        $data['title'] = lang('proposal');
        $data['page_title'] = lang('proposal');
        $data['document_label'] = lang('proposal');
        $data['sales_info'] = get_row('tbl_proposals', array('proposals_id' => $id));
        if (!empty($data['sales_info'])) {
            $data['sales_info']->ref_no = lang('proposal') . ' : ' . $data['sales_info']->reference_no;
            $data['sales_info']->start_date = lang('proposal_date') . ' : ' . display_date($data['sales_info']->proposal_date);
            $url = base_url('frontend/proposals/') . url_encode($id);
            $data['qrcode'] = generate_qrcode($url);
            // check overdue invoice
            if (safe_strtotime($data['sales_info']->due_date) < safe_strtotime(date('Y-m-d')) && $data['sales_info']->status == 'pending' || safe_strtotime($data['sales_info']->due_date) < safe_strtotime(date('Y-m-d')) && $data['sales_info']->status == ('draft')) {
                // check overdue how many days from due_date
                $date1 = new DateTime($data['sales_info']->due_date);
                $date2 = new DateTime(date('Y-m-d'));
                $interval = $date1->diff($date2);
                $overdue_days = $interval->format('%a');
                $data['sales_info']->overdue_days = lang('proposal_overdue') . ' ' . lang('by') . ' ' . $overdue_days . ' ' . lang('days');
            }
            $data['sales_info']->end_date = lang('due_date') . ' : ' . display_date($data['sales_info']->due_date);
            if (!empty($data['sales_info']->user_id)) {
                $data['sales_info']->sales_agent = lang('sales') . ' ' . lang('agent') . ' : ' . fullname($data['sales_info']->user_id);
            }
            $data['sales_info']->status_label = lang($data['sales_info']->status);

            $data['sales_info']->custom_field = '';
            $show_custom_fields = custom_form_label(11, $data['sales_info']->proposals_id);
            if (!empty($show_custom_fields)) {
                foreach ($show_custom_fields as $c_label => $v_fields) {
                    if (!empty($v_fields)) {
                        $data['sales_info']->custom_field .= $c_label . ' : ' . $v_fields . '<br>';
                    }
                }
            }
            if ($data['sales_info']->module == 'client') {
                $clientInfo = get_row('tbl_client', array('client_id' => $data['sales_info']->module_id));
                $data['sales_info'] = (object)array_merge((array)$data['sales_info'], (array)$clientInfo);
            } else if ($data['sales_info']->module == 'leads') {
                $leadsInfo = get_row('tbl_leads', array('leads_id' => $data['sales_info']->module_id));
                // merge $data['sales_info'] and $leadsInfo and make it object
                $data['sales_info'] = (object)array_merge((array)$data['sales_info'], (array)$leadsInfo);
                $data['sales_info']->name = $data['sales_info']->lead_name;
                $data['sales_info']->zipcode = null;
            }
            $data['items_id'] = 'proposals_items_id';
            $data['all_items'] = $this->proposal_model->ordered_items_by_id($data['sales_info']->proposals_id);

            $data['sales_info']->sub_total = ($this->proposal_model->proposal_calculation('proposal_cost', $data['sales_info']->proposals_id));
            $data['sales_info']->discount = ($this->proposal_model->proposal_calculation('discount', $data['sales_info']->proposals_id));
            $data['sales_info']->total = ($this->proposal_model->proposal_calculation('total', $data['sales_info']->proposals_id));
            $data['footer'] = config_item('proposal_footer');
            $data['page_title'] = 'PRO-' . $data['sales_info']->reference_no;
            $data['page_description'] = display_date($data['sales_info']->proposal_date) . ' • ' . lang('due_date') . ': ' . display_date($data['sales_info']->due_date);
            $status_key = strtolower((string) ($data['sales_info']->status ?? ''));
            $status_badges = array(
                'accepted' => 'bg-emerald-50 text-emerald-700 border-emerald-200',
                'declined' => 'bg-rose-50 text-rose-700 border-rose-200',
                'cancelled' => 'bg-rose-50 text-rose-700 border-rose-200',
                'expired' => 'bg-amber-50 text-amber-700 border-amber-200',
                'open' => 'bg-amber-50 text-amber-700 border-amber-200',
                'sent' => 'bg-blue-50 text-blue-700 border-blue-200',
                'revised' => 'bg-blue-50 text-blue-700 border-blue-200',
                'draft' => 'bg-slate-100 text-slate-700 border-slate-200',
                'pending' => 'bg-sky-100 text-sky-700 border-sky-200',
            );
            $status_class = isset($status_badges[$status_key]) ? $status_badges[$status_key] : 'bg-slate-100 text-slate-700 border-slate-200';
            $data['header_badge_html'] = '<span class="inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold ' . $status_class . '">' . html_escape($data['sales_info']->status_label) . '</span>';
            $data['header_actions'] = array();
            $data['header_actions_html'] = '<div class="flex flex-wrap items-center justify-end gap-2">';
            $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $data['sales_info']->proposals_id));
            $can_delete = $this->proposal_model->can_action('tbl_proposals', 'delete', array('proposals_id' => $data['sales_info']->proposals_id));
            $notified_reminder = (int) $this->db
                ->where(array('module' => 'proposal', 'module_id' => $data['sales_info']->proposals_id, 'notified' => 'No'))
                ->count_all_results('tbl_reminders');
            $data['notified_reminder'] = $notified_reminder;

            if (!empty($can_edit) && !empty(can_action('140', 'edited'))) {
                $data['header_actions_html'] .= btn_modal(
                    'admin/proposals/insert_items/' . $data['sales_info']->proposals_id,
                    '<span>' . lang('add_items') . '</span>',
                    lang('add_items'),
                    'lg',
                    'plus',
                    array(
                        'class' => 'inline-flex items-center gap-2 rounded-xl border border-slate-800 bg-slate-800 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-slate-700 dark:border-slate-700 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white',
                    )
                );
            }
            $reminder_label = lang('reminder');
            if (!empty($notified_reminder)) {
                $reminder_label .= ' <span class="ml-1 inline-flex items-center justify-center rounded-full bg-amber-100 px-2 text-[10px] font-bold text-amber-700">' . (int) $notified_reminder . '</span>';
            }
            $data['header_actions_html'] .= btn_modal(
                'admin/invoice/reminder/proposal/' . $data['sales_info']->proposals_id,
                $reminder_label,
                lang('reminder'),
                'lg',
                'bell',
                array('class' => 'inline-flex items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-4 py-2.5 text-sm font-semibold text-amber-700 hover:bg-amber-100')
            );
            if (!empty($can_edit) && !empty(can_action('140', 'edited'))) {
                $data['header_actions_html'] .= btn_modal(
                    'admin/proposals/clone_proposal/' . $data['sales_info']->proposals_id,
                    lang('clone'),
                    lang('clone'),
                    'md',
                    'copy',
                    array('class' => 'inline-flex items-center gap-2 rounded-xl border border-border bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800')
                );
            }
            $more_actions = '<div class="relative" data-dropdown>';
            $more_actions .= '<button type="button" data-dropdown-toggle="proposal-header-actions" class="inline-flex h-11 items-center gap-2 rounded-xl border border-border bg-white px-4 text-sm font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800" title="' . html_escape(lang('more_actions')) . '" aria-label="' . html_escape(lang('more_actions')) . '"><i data-lucide="more-horizontal" class="h-4 w-4"></i><span>' . html_escape(lang('more_actions')) . '</span></button>';
            $more_actions .= '<div id="proposal-header-actions" data-dropdown-menu class="hidden absolute right-0 mt-2 w-56 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-6rem)] overflow-y-auto rounded-xl border border-border bg-card p-2 shadow-lg z-30">';
            $more_actions .= '<a href="' . base_url('admin/proposals/pdf_proposals/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="download" class="h-3.5 w-3.5 text-blue-500"></i><span>' . html_escape(lang('pdf')) . '</span></a>';
            $more_actions .= '<a href="#" onclick="print_sales_details(\'sales_details\'); return false;" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="printer" class="h-3.5 w-3.5 text-slate-500"></i><span>' . html_escape(lang('print')) . '</span></a>';
            $more_actions .= '<a href="' . base_url('admin/proposals/send_proposals_email/' . $data['sales_info']->proposals_id . '/' . true) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="mail" class="h-3.5 w-3.5 text-emerald-500"></i><span>' . html_escape(lang('send_email')) . '</span></a>';
            $more_actions .= '<div class="my-2 border-t border-border"></div>';
            if (!empty($can_edit) && !empty(can_action('140', 'edited'))) {
                if ($data['sales_info']->show_client == 'Yes') {
                    $more_actions .= '<a href="' . base_url('admin/proposals/change_status/hide/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="eye-off" class="h-3.5 w-3.5 text-slate-500"></i><span>' . html_escape(lang('hide_to_client')) . '</span></a>';
                } else {
                    $more_actions .= '<a href="' . base_url('admin/proposals/change_status/show/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="eye" class="h-3.5 w-3.5 text-slate-500"></i><span>' . html_escape(lang('show_to_client')) . '</span></a>';
                }
                if ($data['sales_info']->convert != 'Yes') {
                    $more_actions .= '<a href="#" data-modal-url="' . base_url('admin/proposals/convert_to/invoice/' . $data['sales_info']->proposals_id) . '" data-modal-title="' . html_escape(lang('convert_to_invoice')) . '" data-modal-size="xl" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="repeat" class="h-3.5 w-3.5 text-blue-500"></i><span>' . html_escape(lang('convert') . ' ' . lang('to') . ' ' . lang('invoice')) . '</span></a>';
                    $more_actions .= '<a href="#" data-modal-url="' . base_url('admin/proposals/convert_to/estimate/' . $data['sales_info']->proposals_id) . '" data-modal-title="' . html_escape(lang('convert_to_estimate')) . '" data-modal-size="xl" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="repeat" class="h-3.5 w-3.5 text-blue-500"></i><span>' . html_escape(lang('convert') . ' ' . lang('to') . ' ' . lang('estimate')) . '</span></a>';
                }
                $more_actions .= '<div class="my-2 border-t border-border"></div>';
                $more_actions .= '<a href="' . base_url('admin/proposals/change_status/draft/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="file-text" class="h-3.5 w-3.5 text-slate-500"></i><span>' . html_escape(lang('mark_as_draft')) . '</span></a>';
                $more_actions .= '<a href="' . base_url('admin/proposals/change_status/sent/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="send" class="h-3.5 w-3.5 text-sky-500"></i><span>' . html_escape(lang('mark_as_sent')) . '</span></a>';
                $more_actions .= '<a href="' . base_url('admin/proposals/change_status/revised/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="refresh-cw" class="h-3.5 w-3.5 text-blue-500"></i><span>' . html_escape(lang('mark_as_revised')) . '</span></a>';
                $more_actions .= '<a href="' . base_url('admin/proposals/change_status/open/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="circle-dot" class="h-3.5 w-3.5 text-amber-500"></i><span>' . html_escape(lang('mark_as_open')) . '</span></a>';
                $more_actions .= '<a href="' . base_url('admin/proposals/change_status/declined/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="x-circle" class="h-3.5 w-3.5 text-rose-500"></i><span>' . html_escape(lang('declined')) . '</span></a>';
                $more_actions .= '<a href="' . base_url('admin/proposals/change_status/accepted/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="check-circle-2" class="h-3.5 w-3.5 text-emerald-500"></i><span>' . html_escape(lang('accepted')) . '</span></a>';
                $more_actions .= '<div class="my-2 border-t border-border"></div>';
                $more_actions .= '<a href="' . base_url('admin/proposals/createproposal/edit_proposals/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="pencil" class="h-3.5 w-3.5 text-slate-500"></i><span>' . html_escape(lang('edit') . ' ' . lang('proposal')) . '</span></a>';
            }
            $more_actions .= '<a href="' . base_url('admin/proposals/index/proposals_history/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="history" class="h-3.5 w-3.5 text-slate-500"></i><span>' . html_escape(lang('proposal_history')) . '</span></a>';
            if (!empty($can_delete) && !empty(can_action('140', 'deleted'))) {
                $more_actions .= '<div class="my-2 border-t border-border"></div>';
                $more_actions .= '<a href="' . base_url('admin/proposals/delete/delete_proposals/' . $data['sales_info']->proposals_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-rose-600 transition-colors hover:bg-rose-50"><i data-lucide="trash-2" class="h-3.5 w-3.5"></i><span>' . html_escape(lang('delete')) . '</span></a>';
            }
            $more_actions .= '</div></div>';
            $data['header_actions_html'] .= $more_actions;
            $data['header_actions_html'] .= '</div>';
        } else {
            set_message('error', lang('no_data_found'));
            redirect('admin/proposals');
        }
        if (!empty($pdf)) {
            $this->common_model->sales_pdf($data, $pdf);
            return;
        }
        $data['proposal_pdf_print_html'] = $this->load->view('admin/common/sales_pdf', $data, TRUE);
        $data['subview'] = $this->load->view('admin/proposals/proposals_details', $data, TRUE);
        $this->load->view('admin/_layout_main', $data); //page load
    }

    public function pdf_proposals($id)
    {
        $this->proposals_details($id, true);
    }

    public function save_proposals($id = NULL)
    {
        $created = can_action('140', 'created');
        $edited = can_action('140', 'edited');
        if (!empty($created) || !empty($edited) && !empty($id)) {
            $data = $this->proposal_model->array_from_post(array('reference_no', 'discount_type', 'tags', 'discount_percent', 'user_id', 'adjustment', 'discount_total', 'show_quantity_as'));
            $data['tags'] = normalize_and_sync_tags($data['tags']);
            $data['show_quantity_as'] = strtolower((string) $data['show_quantity_as']);
            if (!in_array($data['show_quantity_as'], array('qty', 'hours', 'qty_hours'), true)) {
                $data['show_quantity_as'] = 'qty';
            }
            if (empty($data['discount_type'])) {
                $data['discount_type'] = 'none';
            }
            $data['proposal_date'] = date('Y-m-d', safe_strtotime($this->input->post('proposal_date', TRUE)));
            if (empty($data['proposal_date'])) {
                $data['proposal_date'] = date('Y-m-d');
            }
            if (empty($data['discount_percent'])) {
                $data['discount_percent'] = 0;
            }
            if (empty($data['discount_total'])) {
                $data['discount_total'] = 0;
            }
            $data['warehouse_id'] = $this->input->post('warehouse_id', TRUE);
            $data['proposal_year'] = date('Y', safe_strtotime($this->input->post('proposal_date', TRUE)));
            $data['proposal_month'] = date('Y-m', safe_strtotime($this->input->post('proposal_date', TRUE)));
            $data['due_date'] = date('Y-m-d', safe_strtotime($this->input->post('due_date', TRUE)));
            $data['notes'] = $this->input->post('notes', TRUE);

            $tax['tax_name'] = $this->input->post('total_tax_name', TRUE);
            $tax['total_tax'] = $this->input->post('total_tax', TRUE);
            $data['total_tax'] = json_encode($tax);
            $i_tax = 0;
            if (!empty($tax['total_tax'])) {
                foreach ($tax['total_tax'] as $v_tax) {
                    $i_tax += $v_tax;
                }
            }
            $data['tax'] = $i_tax;
            $save_as_draft = $this->input->post('status', TRUE);
            if (!empty($save_as_draft)) {
                $data['status'] = $save_as_draft;
            } else {
                $data['status'] = 'draft';
            }
            $data['module'] = $this->input->post('module', true);
            if (!empty($data['module']) && $data['module'] == 'leads') {
                $data['module_id'] = $this->input->post('leads_id', true);
                $curren = $this->input->post('currency', true);
            } else {
                $data['module_id'] = $this->input->post('client_id', true);

                $currency = $this->proposal_model->client_currency_symbol($data['module_id']);
                if (!empty($currency->code)) {
                    $curren = $currency->code;
                } else {
                    $curren = config_item('default_currency');
                }
            }
            $data['currency'] = $curren;


            $permission = $this->input->post('permission', true);
            if (!empty($permission)) {
                if ($permission == 'everyone') {
                    $assigned = 'all';
                } else {
                    $assigned_to = $this->proposal_model->array_from_post(array('assigned_to'));
                    if (!empty($assigned_to['assigned_to'])) {
                        foreach ($assigned_to['assigned_to'] as $assign_user) {
                            $assigned[$assign_user] = $this->input->post('action_' . $assign_user, true);
                        }
                    }
                }
                if (!empty($assigned)) {
                    if ($assigned != 'all') {
                        $assigned = json_encode($assigned);
                    }
                } else {
                    $assigned = 'all';
                }
                $data['permission'] = $assigned;
            } else {
                set_message('error', lang('assigned_to') . ' Field is required');
                if (empty($_SERVER['HTTP_REFERER'])) {
                    redirect('admin/proposals');
                } else {
                    redirect($_SERVER['HTTP_REFERER']);
                }
            }

            // get all client
            $this->proposal_model->_table_name = 'tbl_proposals';
            $this->proposal_model->_primary_key = 'proposals_id';
            if (!empty($id)) {
                $proposals_id = $id;
                $this->proposal_model->save($data, $id);
                $action = ('activity_proposals_updated');
                $msg = lang('proposals_updated');
                $description = 'not_proposal_updated';
            } else {
                $proposals_id = $this->proposal_model->save($data);

                $action = ('activity_proposals_created');
                $msg = lang('proposals_created');
                $description = 'not_proposal_created';
            }
            // print('<pre>' . print_r($proposals_id, true) . '</pre>');
            // exit;

            save_custom_field(11, $proposals_id);


            $removed_items = $this->input->post('removed_items', TRUE);
            if (!empty($removed_items)) {
                foreach ($removed_items as $r_id) {
                    if ($r_id != 'undefined') {
                        $this->db->where('proposals_items_id', $r_id);
                        $this->db->delete('tbl_proposals_items');
                    }
                }
            }

            $itemsid = $this->input->post('proposals_items_id', TRUE);
            $items_data = $this->input->post('items', true);

            if (!empty($items_data)) {
                $index = 0;
                foreach ($items_data as $items) {
                    $items['proposals_id'] = $proposals_id;
                    $items_id = null;
                    if (!empty($items['items_id']) && $items['items_id'] != 'undefined') {
                        $items_id = $items['items_id'];
                    } elseif (!empty($items['proposals_items_id']) && $items['proposals_items_id'] != 'undefined') {
                        $items_id = $items['proposals_items_id'];
                    }

                    unset($items['items_id']);
                    unset($items['estimate_items_id']);
                    unset($items['invoice_items_id']);
                    unset($items['credit_note_items_id']);
                    unset($items['proposals_items_id']);
                    unset($items['total_qty']);
                    $tax = 0;
                    if (!empty($items['taxname'])) {
                        foreach ($items['taxname'] as $tax_name) {
                            $tax_rate = explode("|", $tax_name);
                            $tax += $tax_rate[1];
                        }
                        $items['item_tax_name'] = $items['taxname'];
                        unset($items['taxname']);
                        $items['item_tax_name'] = json_encode($items['item_tax_name']);
                    }

                    if (empty($items['saved_items_id']) || $items['saved_items_id'] == 'undefined') {
                        $items['saved_items_id'] = 0;
                    }

                    $price = $items['quantity'] * $items['unit_cost'];
                    $items['item_tax_total'] = ($price / 100 * $tax);
                    $items['total_cost'] = $price;
                    // get all client
                    $this->proposal_model->_table_name = 'tbl_proposals_items';
                    $this->proposal_model->_primary_key = 'proposals_items_id';

                    if (!empty($items_id)) {
                        $this->proposal_model->save($items, $items_id);
                    } else {
                        $items_id = $this->proposal_model->save($items);
                    }
                    $index++;
                }
            }
            $activity = array(
                'user' => $this->session->userdata('user_id'),
                'module' => 'proposals',
                'module_field_id' => $proposals_id,
                'activity' => $action,
                'icon' => 'fa-shopping-cart',
                'link' => 'admin/proposals/index/proposals_details/' . $proposals_id,
                'value1' => $data['reference_no']
            );
            $this->proposal_model->_table_name = 'tbl_activities';
            $this->proposal_model->_primary_key = 'activities_id';
            $this->proposal_model->save($activity);

            // send notification to client
            if (!empty($data['client_id'])) {
                $client_info = $this->proposal_model->check_by(array('client_id' => $data['client_id']), 'tbl_client');
                if (!empty($client_info->primary_contact)) {
                    $notifyUser = array($client_info->primary_contact);
                } else {
                    $user_info = $this->proposal_model->check_by(array('company' => $data['client_id']), 'tbl_account_details');
                    if (!empty($user_info)) {
                        $notifyUser = array($user_info->user_id);
                    }
                }
            }
            if (!empty($notifyUser)) {
                foreach ($notifyUser as $v_user) {
                    if ($v_user != $this->session->userdata('user_id')) {
                        add_notification(array(
                            'to_user_id' => $v_user,
                            'icon' => 'shopping-cart',
                            'description' => $description,
                            'link' => 'client/proposals/index/proposals_details/' . $proposals_id,
                            'value' => $data['reference_no'],
                        ));
                    }
                }
                show_notification($notifyUser);
            }

            // messages for user
            $type = "success";
            $message = $msg;
            set_message($type, $message);
        }
        redirect('admin/proposals/index/proposals_details/' . $proposals_id);
    }

    public function createproposal($action = NULL, $id = NULL, $item_id = NULL)
    {
        if (is_numeric($action) && empty($id)) {
            $id = (int) $action;
            $action = 'edit_proposals';
        }
        $data['page'] = lang('sales');
        $data['sub_active'] = lang('proposals');
        if (!empty($item_id)) {
            $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $id));
            if (!empty($can_edit)) {
                $data['item_info'] = $this->proposal_model->check_by(array('proposals_items_id' => $item_id), 'tbl_proposals_items');
            }
        }
        if ($action == 'edit_proposals') {
            $data['active'] = 2;
            $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $id));
            if (!empty($can_edit)) {
                $data['proposals_info'] = $this->proposal_model->check_by(array('proposals_id' => $id), 'tbl_proposals');
            }
        } else if ($action == 'client' || $action == 'leads') {
            $data['module_id'] = $id;
            $data['module'] = $action;
            $data['active'] = 2;
        } else {
            $data['active'] = 1;
        }
        // get permission user
        $data['permission_user'] = $this->proposal_model->all_permission_user('140');

        $data['title'] = lang('proposals'); //Page title
        $is_edit = !empty($data['proposals_info']);
        $data['page_title'] = $is_edit ? (lang('edit') . ' ' . lang('proposal')) : lang('create_proposal');
        $data['page_description'] = $is_edit ? (lang('manage') . ' ' . lang('proposal') . ' #' . $data['proposals_info']->reference_no) : (lang('manage') . ' ' . lang('proposal'));
        $data['header_badge_html'] = '<span class="inline-flex items-center rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs font-semibold text-slate-700">' . html_escape($is_edit ? lang('draft') : lang('new')) . '</span>';
        $data['header_actions'] = array();
        $data['header_actions_html'] = '';
        $data['header_actions'][] = array(
            'label' => lang('all_proposals'),
            'icon' => 'list',
            'href' => base_url('admin/proposals'),
            'style' => 'neutral',
        );
        if ($is_edit) {
            $data['header_actions'][] = array(
                'label' => lang('create_proposal'),
                'icon' => 'plus',
                'href' => base_url('admin/proposals/createproposal'),
                'style' => 'primary',
            );
        }
        $data['header_filters'] = array();
        $data['header_filter_extras_html'] = '';
        $subview = 'createproposal';

        $data['subview'] = $this->load->view('admin/proposals/' . $subview, $data, TRUE);
        $this->load->view('admin/_layout_main', $data); //page load
    }

    public function insert_items($proposals_id)
    {
        $edited = can_action('140', 'edited');
        $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $proposals_id));
        if (!empty($can_edit) && !empty($edited)) {
            $data['proposals_id'] = $proposals_id;
            $data['modal_subview'] = $this->load->view('admin/proposals/_modal_insert_items', $data, FALSE);
        } else {
            set_message('error', lang('there_in_no_value'));
            if (empty($_SERVER['HTTP_REFERER'])) {
                redirect('admin/proposals');
            } else {
                redirect($_SERVER['HTTP_REFERER']);
            }
        }
    }

    public function add_insert_items($proposals_id)
    {
        $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $proposals_id));
        $edited = can_action('140', 'edited');
        if (!empty($can_edit) && !empty($edited)) {
            $saved_items_id = $this->input->post('saved_items_id', TRUE);
            if (!empty($saved_items_id)) {
                foreach ($saved_items_id as $v_items_id) {
                    $items_info = $this->proposal_model->check_by(array('saved_items_id' => $v_items_id), 'tbl_saved_items');
                    $tax_info = json_decode($items_info->tax_rates_id);
                    $tax_name = array();
                    if (is_array($tax_info) && !empty($tax_info)) {
                        foreach ($tax_info as $v_tax) {
                            $all_tax = $this->db->where('tax_rates_id', $v_tax)->get('tbl_tax_rates')->row();
                            if (!empty($all_tax)) {
                                $tax_name[] = $all_tax->tax_rate_name . '|' . $all_tax->tax_rate_percent;
                            }
                        }
                    }
                    if (!empty($tax_name)) {
                        $tax_name = $tax_name;
                    } else {
                        $tax_name = array();
                    }

                    $data['quantity'] = 1;
                    $data['proposals_id'] = $proposals_id;
                    $data['item_name'] = $items_info->item_name;
                    $data['item_desc'] = $items_info->item_desc;
                    $data['hsn_code'] = $items_info->hsn_code;
                    $data['unit_cost'] = $items_info->unit_cost;
                    $data['item_tax_rate'] = '0.00';
                    $data['item_tax_name'] = json_encode($tax_name);
                    $data['item_tax_total'] = $items_info->item_tax_total;
                    $data['total_cost'] = $items_info->unit_cost;

                    $this->proposal_model->_table_name = 'tbl_proposals_items';
                    $this->proposal_model->_primary_key = 'proposals_items_id';
                    $items_id = $this->proposal_model->save($data);
                    $action = 'activity_proposal_items_added';
                    $msg = lang('proposals_item_save');
                    $activity = array(
                        'user' => $this->session->userdata('user_id'),
                        'module' => 'proposals',
                        'module_field_id' => $items_id,
                        'activity' => $action,
                        'icon' => 'fa-shopping-cart',
                        'link' => 'admin/proposals/index/proposals_details/' . $proposals_id,
                        'value1' => $items_info->item_name
                    );
                    $this->proposal_model->_table_name = 'tbl_activities';
                    $this->proposal_model->_primary_key = 'activities_id';
                    $this->proposal_model->save($activity);
                }
                $type = "success";
                $this->update_invoice_tax($saved_items_id, $proposals_id);
            } else {
                $type = "error";
                $msg = 'Please Select a items';
            }
            $message = $msg;
            set_message($type, $message);
            if ($this->input->is_ajax_request()) {
                echo json_encode(array(
                    'status' => $type,
                    'message' => $message,
                    'url' => 'admin/proposals/proposals_details/' . $proposals_id,
                ));
                return;
            }
            redirect('admin/proposals/index/proposals_details/' . $proposals_id);
        } else {
            $message = lang('there_in_no_value');
            set_message('error', $message);
            if ($this->input->is_ajax_request()) {
                echo json_encode(array('status' => 'error', 'message' => $message));
                return;
            }
            if (empty($_SERVER['HTTP_REFERER'])) {
                redirect('admin/proposals');
            } else {
                redirect($_SERVER['HTTP_REFERER']);
            }
        }
    }

    function update_invoice_tax($saved_items_id, $proposals_id)
    {

        $invoice_info = $this->proposal_model->check_by(array('proposals_id' => $proposals_id), 'tbl_proposals');
        $tax_info = json_decode($invoice_info->total_tax);

        $tax_name = is_object($tax_info) && !empty($tax_info->tax_name) ? $tax_info->tax_name : array();
        $total_tax = is_object($tax_info) && !empty($tax_info->total_tax) ? $tax_info->total_tax : array();
        $invoice_tax = array();
        if (!empty($tax_name)) {
            foreach ($tax_name as $t_key => $v_tax_info) {
                array_push($invoice_tax, array('tax_name' => $v_tax_info, 'total_tax' => !empty($total_tax[$t_key]) ? $total_tax[$t_key] : 0));
            }
        }
        $all_tax_info = array();
        if (!empty($saved_items_id)) {
            foreach ($saved_items_id as $v_items_id) {
                $items_info = $this->proposal_model->check_by(array('saved_items_id' => $v_items_id), 'tbl_saved_items');

                $tax_info = json_decode($items_info->tax_rates_id);
                if (is_array($tax_info) && !empty($tax_info)) {
                    foreach ($tax_info as $v_tax) {
                        $all_tax = $this->db->where('tax_rates_id', $v_tax)->get('tbl_tax_rates')->row();
                        if (!empty($all_tax)) {
                            array_push($all_tax_info, array('tax_name' => $all_tax->tax_rate_name . '|' . $all_tax->tax_rate_percent, 'total_tax' => $items_info->unit_cost / 100 * $all_tax->tax_rate_percent));
                        }
                    }
                }
            }
        }
        if (!empty($invoice_tax) && is_array($invoice_tax) && !empty($all_tax_info)) {
            $all_tax_info = array_merge($all_tax_info, $invoice_tax);
        }

        $results = array();
        foreach ($all_tax_info as $value) {
            if (!isset($results[$value['tax_name']])) {
                $results[$value['tax_name']] = 0;
            }
            $results[$value['tax_name']] += $value['total_tax'];
        }
        if (!empty($results)) {
            foreach ($results as $key => $value) {
                $structured_results['tax_name'][] = $key;
                $structured_results['total_tax'][] = $value;
            }
            $invoice_data['tax'] = array_sum($structured_results['total_tax']);
            $invoice_data['total_tax'] = json_encode($structured_results);

            $this->proposal_model->_table_name = 'tbl_proposals';
            $this->proposal_model->_primary_key = 'proposals_id';
            $this->proposal_model->save($invoice_data, $proposals_id);
        }
        return true;
    }

    public function add_item($id = NULL)
    {
        $data = $this->proposal_model->array_from_post(array('proposals_id', 'item_order'));
        $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $data['proposals_id']));
        $edited = can_action('140', 'edited');
        if (!empty($can_edit) && !empty($edited)) {
            $quantity = $this->input->post('quantity', TRUE);
            $array_data = $this->proposal_model->array_from_post(array('item_name', 'item_desc', 'item_tax_rate', 'unit_cost'));
            if (!empty($quantity)) {
                foreach ($quantity as $key => $value) {
                    $data['quantity'] = $value;
                    $data['item_name'] = $array_data['item_name'][$key];
                    $data['item_desc'] = $array_data['item_desc'][$key];
                    $data['unit_cost'] = $array_data['unit_cost'][$key];
                    $data['item_tax_rate'] = $array_data['item_tax_rate'][$key];
                    $sub_total = $data['unit_cost'] * $data['quantity'];

                    $data['item_tax_total'] = ($data['item_tax_rate'] / 100) * $sub_total;
                    $data['total_cost'] = $sub_total + $data['item_tax_total'];

                    // get all client
                    $this->proposal_model->_table_name = 'tbl_proposals_items';
                    $this->proposal_model->_primary_key = 'proposals_items_id';
                    if (!empty($id)) {
                        $proposals_items_id = $id;
                        $this->proposal_model->save($data, $id);
                        $action = ('activity_proposals_items_updated');
                    } else {
                        $proposals_items_id = $this->proposal_model->save($data);
                        $action = 'activity_proposals_items_added';
                    }
                    $activity = array(
                        'user' => $this->session->userdata('user_id'),
                        'module' => 'proposals',
                        'module_field_id' => $proposals_items_id,
                        'activity' => $action,
                        'icon' => 'fa-shopping-cart',
                        'value1' => $data['item_name']
                    );
                    $this->proposal_model->_table_name = 'tbl_activities';
                    $this->proposal_model->_primary_key = 'activities_id';
                    $this->proposal_model->save($activity);
                }
            }
            // messages for user
            $type = "success";
            $message = lang('proposals_item_save');
            set_message($type, $message);
            redirect('admin/proposals/index/proposals_details/' . $data['proposals_id']);
        } else {
            set_message('error', lang('there_in_no_value'));
            if (empty($_SERVER['HTTP_REFERER'])) {
                redirect('admin/proposals');
            } else {
                redirect($_SERVER['HTTP_REFERER']);
            }
        }
    }

    public
    function clone_proposal($proposals_id)
    {
        $edited = can_action('140', 'edited');
        $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $proposals_id));
        if (!empty($can_edit) && !empty($edited)) {
            $data['proposals_info'] = $this->proposal_model->check_by(array('proposals_id' => $proposals_id), 'tbl_proposals');
            // get all client
            $this->proposal_model->_table_name = 'tbl_client';
            $this->proposal_model->_order_by = 'client_id';
            $data['all_client'] = $this->proposal_model->get();

            $data['modal_subview'] = $this->load->view('admin/proposals/_modal_clone_proposals', $data, FALSE);
        } else {
            set_message('error', lang('there_in_no_value'));
            if (empty($_SERVER['HTTP_REFERER'])) {
                redirect('admin/proposals');
            } else {
                redirect($_SERVER['HTTP_REFERER']);
            }
        }
    }

    public
    function cloned_proposals($id)
    {
        $edited = can_action('140', 'edited');
        $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $id));
        if (!empty($can_edit) && !empty($edited)) {
            if (config_item('increment_proposals_number') == 'FALSE') {
                $this->load->helper('string');
                $reference_no = config_item('proposal_prefix') . ' ' . random_string('nozero', 6);
            } else {
                $reference_no = config_item('proposal_prefix') . ' ' . $this->proposal_model->generate_proposal_number();
            }

            $invoice_info = $this->proposal_model->check_by(array('proposals_id' => $id), 'tbl_proposals');
            $module = $this->input->post('module', true);
            if (empty($module)) {
                $module = $invoice_info->module;
                $module_id = $invoice_info->module_id;
                $currency = $invoice_info->currency;
            } else {
                if ($module == 'leads') {
                    $module_id = $this->input->post('leads_id', true);
                    $currency = $this->input->post('currency', true);
                } else {
                    $module_id = $this->input->post('client_id', true);
                    $currenc = $this->proposal_model->client_currency_symbol($module_id);
                    $currency = !empty($currenc->code) ? $currenc->code : $invoice_info->currency;
                }
            }
            $proposal_date = $this->normalize_proposal_date($this->input->post('proposal_date', TRUE), $invoice_info->proposal_date);
            $due_date = $this->normalize_proposal_date($this->input->post('due_date', TRUE), $invoice_info->due_date);
            // save into invoice table
            $new_invoice = array(
                'reference_no' => $reference_no,
                'subject' => $invoice_info->subject,
                'module' => $module,
                'module_id' => $module_id,
                'proposal_date' => $proposal_date,
                'proposal_month' => date('Y-m', safe_strtotime($proposal_date)),
                'proposal_year' => date('Y', safe_strtotime($proposal_date)),
                'due_date' => $due_date,
                'notes' => $invoice_info->notes,
                'tags' => $invoice_info->tags,
                'total_tax' => $invoice_info->total_tax,
                'tax' => $invoice_info->tax,
                'discount_type' => $invoice_info->discount_type,
                'discount_percent' => $invoice_info->discount_percent,
                'user_id' => $invoice_info->user_id,
                'adjustment' => $invoice_info->adjustment,
                'discount_total' => $invoice_info->discount_total,
                'show_quantity_as' => $invoice_info->show_quantity_as,
                'currency' => $currency,
                'status' => $invoice_info->status,
                'date_sent' => $invoice_info->date_sent,
                'emailed' => $invoice_info->emailed,
                'show_client' => $invoice_info->show_client,
                'convert' => $invoice_info->convert,
                'convert_module' => $invoice_info->convert_module,
                'convert_module_id' => $invoice_info->convert_module_id,
                'converted_date' => $invoice_info->converted_date,
                'permission' => $invoice_info->permission,
            );
            $this->proposal_model->_table_name = "tbl_proposals"; //table name
            $this->proposal_model->_primary_key = "proposals_id";
            $new_invoice_id = $this->proposal_model->save($new_invoice);

            $invoice_items = $this->db->where('proposals_id', $id)->get('tbl_proposals_items')->result();

            if (!empty($invoice_items)) {
                foreach ($invoice_items as $new_item) {
                    $items = array(
                        'proposals_id' => $new_invoice_id,
                        'item_name' => $new_item->item_name,
                        'item_desc' => $new_item->item_desc,
                        'unit_cost' => $new_item->unit_cost,
                        'quantity' => $new_item->quantity,
                        'item_tax_rate' => $new_item->item_tax_rate,
                        'item_tax_name' => $new_item->item_tax_name,
                        'item_tax_total' => $new_item->item_tax_total,
                        'total_cost' => $new_item->total_cost,
                        'unit' => $new_item->unit,
                        'order' => $new_item->order,
                    );
                    $this->proposal_model->_table_name = "tbl_proposals_items"; //table name
                    $this->proposal_model->_primary_key = "proposals_items_id";
                    $this->proposal_model->save($items);
                }
            }
            // save into activities
            $activities = array(
                'user' => $this->session->userdata('user_id'),
                'module' => 'proposals',
                'module_field_id' => $new_invoice_id,
                'activity' => ('activity_clone_proposal'),
                'icon' => 'fa-shopping-cart',
                'link' => 'admin/proposals/index/proposals_details/' . $new_invoice_id,
                'value1' => ' from ' . $invoice_info->reference_no . ' to ' . $reference_no,
            );
            // Update into tbl_project
            $this->proposal_model->_table_name = "tbl_activities"; //table name
            $this->proposal_model->_primary_key = "activities_id";
            $this->proposal_model->save($activities);

            // messages for user
            $type = "success";
            $message = lang('proposals_created');
            set_message($type, $message);
				if ($this->input->is_ajax_request()) {
				echo json_encode(array("status" => $type, 'message' => $message));
				exit();
			}

        } else {
            if ($this->input->is_ajax_request()) {
			echo json_encode(array("status" => 'error', 'message' => lang('there_in_no_value')));
			exit();
		}
        }
    }

    public function change_status($action, $id)
    {
        $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $id));
        $edited = can_action('140', 'edited');
        if (!empty($can_edit) && !empty($edited)) {
            $where = array('proposals_id' => $id);
            if ($action == 'hide') {
                $data = array('show_client' => 'No');
            } elseif ($action == 'show') {
                $data = array('show_client' => 'Yes');
            } elseif ($action == 'sent') {
                $data = array('emailed' => 'Yes', 'date_sent' => date("Y-m-d H:i:s", time()), 'status' => 'sent');
            } elseif (!empty($action)) {
                $data = array('status' => $action);
            } else {
                $data = array('show_client' => 'Yes');
            }
            $this->proposal_model->set_action($where, $data, 'tbl_proposals');
            // messages for user
            $type = "success";
            $message = lang('proposals_status', $action);
            set_message($type, $message);
            redirect('admin/proposals/index/proposals_details/' . $id);
        } else {
            set_message('error', lang('there_in_no_value'));
            if (empty($_SERVER['HTTP_REFERER'])) {
                redirect('admin/proposals');
            } else {
                redirect($_SERVER['HTTP_REFERER']);
            }
        }
    }

    public
    function delete($action, $proposals_id, $item_id = NULL)
    {
        $can_delete = $this->proposal_model->can_action('tbl_proposals', 'delete', array('proposals_id' => $proposals_id));
        $deleted = can_action('140', 'deleted');
        if (!empty($can_delete) && !empty($deleted)) {
            if ($action == 'delete_item') {
                $this->proposal_model->_table_name = 'tbl_proposals_items';
                $this->proposal_model->_primary_key = 'proposals_items_id';
                $this->proposal_model->delete($item_id);
            } elseif ($action == 'delete_proposals') {

                $this->proposal_model->_table_name = 'tbl_proposals_items';
                $this->proposal_model->delete_multiple(array('proposals_id' => $proposals_id));

                $this->proposal_model->_table_name = 'tbl_reminders';
                $this->proposal_model->delete_multiple(array('module' => 'proposal', 'module_id' => $proposals_id));

                $this->proposal_model->_table_name = 'tbl_proposals';
                $this->proposal_model->_primary_key = 'proposals_id';
                $this->proposal_model->delete($proposals_id);
            }
            $activity = array(
                'user' => $this->session->userdata('user_id'),
                'module' => 'proposals',
                'module_field_id' => $proposals_id,
                'activity' => ('activity_' . $action),
                'icon' => 'fa-shopping-cart',
                'link' => 'admin/proposals/index/proposals_details/' . $proposals_id,
                'value1' => $action
            );

            $this->proposal_model->_table_name = 'tbl_activities';
            $this->proposal_model->_primary_key = 'activities_id';
            $this->proposal_model->save($activity);
            $type = 'success';

            if ($action == 'delete_item') {
                $text = lang('proposals_item_deleted');
                echo json_encode(array("status" => $type, 'message' => $text));
                exit();
            } else {
                $text = lang('proposals_deleted');
                echo json_encode(array("status" => $type, 'message' => $text));
                exit();
            }
        } else {
            echo json_encode(array("status" => 'error', 'message' => lang('there_in_no_value')));
            exit();
        }
    }

    public function send_proposals_email($proposals_id, $row = null)
    {
        if (!empty($row)) {
            $email_template = email_templates(array('email_group' => 'proposal_email'));
            $proposals_info = $this->proposal_model->check_by(array('proposals_id' => $proposals_id), 'tbl_proposals');
            if ($proposals_info->module == 'client') {
                $client_info = $this->proposal_model->check_by(array('client_id' => $proposals_info->module_id), 'tbl_client');
                $client = $client_info->name;
                $currency = $this->proposal_model->client_currency_symbol($proposals_info->module_id);
                $email_template = email_templates(array('email_group' => 'proposal_email'), $proposals_info->module_id);
            } else if ($proposals_info->module == 'leads') {
                $client_info = $this->proposal_model->check_by(array('leads_id' => $proposals_info->module_id), 'tbl_leads');
                $client = $client_info->lead_name;
                $currency = $this->proposal_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
            } else {
                $client = '-';
                $currency = $this->proposal_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
            }

            $amount = $this->proposal_model->proposal_calculation('total', $proposals_info->proposals_id);
            $currency = $currency->code;
            $message = $email_template->template_body;
            $ref = $proposals_info->reference_no;
            $subject = $email_template->subject;
        } else {
            $message = $this->input->post('message', TRUE);
            $ref = $this->input->post('ref', TRUE);
            $subject = $this->input->post('subject', TRUE);
            $client = $this->input->post('client_name', TRUE);
            $amount = $this->input->post('amount', true);
            $currency = $this->input->post('currency', TRUE);
        }

        $client_name = str_replace("{CLIENT}", $client, $message);
        $Ref = str_replace("{PROPOSAL_REF}", $ref, $client_name);
        $Amount = str_replace("{AMOUNT}", $amount, $Ref);
        $Currency = str_replace("{CURRENCY}", $currency, $Amount);
        $link = str_replace("{PROPOSAL_LINK}", base_url() . 'frontend/proposals/' . url_encode($proposals_id), $Currency);
        $message = str_replace("{SITE_NAME}", config_item('company_name'), $link);

        $this->send_email_proposals($proposals_id, $message, $subject); // Email proposals

        $data = array('status' => 'sent', 'emailed' => 'Yes', 'date_sent' => date("Y-m-d H:i:s", time()));

        $this->proposal_model->_table_name = 'tbl_proposals';
        $this->proposal_model->_primary_key = 'proposals_id';
        $this->proposal_model->save($data, $proposals_id);

        // Log Activity
        $activity = array(
            'user' => $this->session->userdata('user_id'),
            'module' => 'proposals',
            'module_field_id' => $proposals_id,
            'activity' => 'activity_proposals_sent',
            'icon' => 'fa-shopping-cart',
            'link' => 'admin/proposals/index/proposals_details/' . $proposals_id,
            'value1' => $ref
        );
        $this->proposal_model->_table_name = 'tbl_activities';
        $this->proposal_model->_primary_key = 'activities_id';
        $this->proposal_model->save($activity);

        $type = 'success';
        $text = lang('proposals_email_sent');
        set_message($type, $text);
        redirect('admin/proposals/index/proposals_details/' . $proposals_id);
    }

    function send_email_proposals($proposals_id, $message, $subject)
    {
        $proposals_info = $this->proposal_model->check_by(array('proposals_id' => $proposals_id), 'tbl_proposals');
        if ($proposals_info->module == 'client') {
            $client_info = $this->proposal_model->check_by(array('client_id' => $proposals_info->module_id), 'tbl_client');
            $email = $client_info->email;
        } else if ($proposals_info->module == 'leads') {
            $client_info = $this->proposal_model->check_by(array('leads_id' => $proposals_info->module_id), 'tbl_leads');
            $email = $client_info->email;
        } else {
            $email = '-';
        }
        $recipient = $email;

        $data['message'] = $message;

        $message = $this->load->view('email_template', $data, TRUE);
        $params = array(
            'recipient' => $recipient,
            'subject' => $subject,
            'message' => $message
        );
        $params['resourceed_file'] = 'uploads/' . slug_it(lang('proposals') . '_pdf_' . $proposals_info->reference_no) . '.pdf';
        $params['resourcement_url'] = base_url() . 'uploads/' . slug_it(lang('proposals') . '_pdf_' . $proposals_info->reference_no) . '.pdf';

        $this->attach_pdf($proposals_id);

        $this->proposal_model->send_email($params);
        //Delete estimate in tmp folder
        if (is_file('uploads/' . slug_it(lang('proposals') . '_pdf_' . $proposals_info->reference_no) . '.pdf')) {
            unlink('uploads/' . slug_it(lang('proposals') . '_pdf_' . $proposals_info->reference_no) . '.pdf');
        }
        // send notification to client
        if ($proposals_info->module == 'client') {
            if (!empty($client_info->primary_contact)) {
                $notifyUser = array($client_info->primary_contact);
            } else {
                $user_info = $this->proposal_model->check_by(array('company' => $proposals_info->module_id), 'tbl_account_details');
                if (!empty($user_info)) {
                    $notifyUser = array($user_info->user_id);
                }
            }
            if (!empty($notifyUser)) {
                foreach ($notifyUser as $v_user) {
                    if ($v_user != $this->session->userdata('user_id')) {
                        add_notification(array(
                            'to_user_id' => $v_user,
                            'icon' => 'shopping-cart',
                            'description' => 'not_email_send_alert',
                            'link' => 'client/proposals/index/proposals_details/' . $proposals_id,
                            'value' => lang('estimate') . ' ' . $proposals_info->reference_no,
                        ));
                    }
                }
                show_notification($notifyUser);
            }
        }
    }

    public function attach_pdf($id)
    {
        $this->proposals_details($id, 'attach');
    }

    function proposals_email($proposals_id)
    {
        $data['proposals_info'] = $this->proposal_model->check_by(array('proposals_id' => $proposals_id), 'tbl_proposals');
        $proposals_info = $data['proposals_info'];
        $client_info = $this->proposal_model->check_by(array('client_id' => $data['proposals_info']->client_id), 'tbl_client');

        $recipient = $client_info->email;

        $message = $this->load->view('admin/proposals/proposals_pdf', $data, TRUE);

        $data['message'] = $message;

        $message = $this->load->view('email_template', $data, TRUE);
        $params = array(
            'recipient' => $recipient,
            'subject' => '[ ' . config_item('company_name') . ' ]' . ' New proposals' . ' ' . $data['proposals_info']->reference_no,
            'message' => $message
        );
        $params['resourceed_file'] = '';

        $this->proposal_model->send_email($params);

        $data = array('status' => 'sent', 'emailed' => 'Yes', 'date_sent' => date("Y-m-d H:i:s", time()));

        $this->proposal_model->_table_name = 'tbl_proposals';
        $this->proposal_model->_primary_key = 'proposals_id';
        $this->proposal_model->save($data, $proposals_id);

        // Log Activity
        $activity = array(
            'user' => $this->session->userdata('user_id'),
            'module' => 'proposals',
            'module_field_id' => $proposals_id,
            'activity' => 'activity_proposals_sent',
            'icon' => 'fa-shopping-cart',
            'link' => 'admin/proposals/index/proposals_details/' . $proposals_id,
            'value1' => $proposals_info->reference_no
        );
        $this->proposal_model->_table_name = 'tbl_activities';
        $this->proposal_model->_primary_key = 'activities_id';
        $this->proposal_model->save($activity);

        // send notification to client
        if (!empty($client_info->primary_contact)) {
            $notifyUser = array($client_info->primary_contact);
        } else {
            $user_info = $this->proposal_model->check_by(array('company' => $proposals_info->client_id), 'tbl_account_details');
            if (!empty($user_info)) {
                $notifyUser = array($user_info->user_id);
            }
        }
        if (!empty($notifyUser)) {
            foreach ($notifyUser as $v_user) {
                if ($v_user != $this->session->userdata('user_id')) {
                    add_notification(array(
                        'to_user_id' => $v_user,
                        'icon' => 'shopping-cart',
                        'description' => 'not_email_send_alert',
                        'link' => 'client/proposals/index/proposals_details/' . $proposals_id,
                        'value' => lang('estimate') . ' ' . $proposals_info->reference_no,
                    ));
                }
            }
            show_notification($notifyUser);
        }

        $type = 'success';
        $text = lang('proposals_email_sent');
        set_message($type, $text);
        redirect('admin/proposals/index/proposals_details/' . $proposals_id);
    }

    public
    function convert_to($type, $id)
    {

        $data['title'] = lang('convert') . ' ' . lang($type);
        $edited = can_action('140', 'edited');
        $can_edit = $this->proposal_model->can_action('tbl_proposals', 'edit', array('proposals_id' => $id));
        if (!empty($can_edit) && !empty($edited)) {
            // get all client
            $this->proposal_model->_table_name = 'tbl_client';
            $this->proposal_model->_order_by = 'client_id';
            $data['all_client'] = $this->proposal_model->get();
            // get permission user
            $data['permission_user'] = $this->proposal_model->all_permission_user('140');

            $data['proposals_info'] = $this->proposal_model->check_by(array('proposals_id' => $id), 'tbl_proposals');

            $data['modal_subview'] = $this->load->view('admin/proposals/convert_to_' . $type, $data, FALSE);
        } else {
            set_message('error', lang('there_in_no_value'));
            if (empty($_SERVER['HTTP_REFERER'])) {
                redirect('admin/proposals');
            } else {
                redirect($_SERVER['HTTP_REFERER']);
            }
        }
    }

    public function converted_to_invoice($proposal_id)
    {
        $data = $this->proposal_model->array_from_post(array('reference_no', 'client_id', 'project_id', 'warehouse_id', 'discount_type', 'discount_percent', 'user_id', 'adjustment', 'discount_total', 'show_quantity_as'));
        $this->db->trans_begin();
        $stock_ok = true;
        $stock_error = lang('stock_update_failed');
        if (!empty($data['reference_no']) && $this->db->where('reference_no', $data['reference_no'])->count_all_results('tbl_invoices') > 0) {
            $data['reference_no'] = $this->proposal_model->generate_invoice_number();
        }

        $all_payment = get_result('tbl_online_payment');
        foreach ($all_payment as $payment) {
            $allow_gateway = 'allow_' . slug_it(strtolower($payment->gateway_name));
            $gateway_status = slug_it(strtolower($payment->gateway_name)) . '_status';
            if (config_item($gateway_status) == 'active') {
                $data[$allow_gateway] = ($this->input->post($allow_gateway) == 'Yes') ? 'Yes' : 'No';
            }
        }

        $data['client_visible'] = ($this->input->post('client_visible') == 'Yes') ? 'Yes' : 'No';
        $data['invoice_date'] = date('Y-m-d', safe_strtotime($this->input->post('invoice_date', TRUE)));
        if (empty($data['invoice_date'])) {
            $data['invoice_date'] = date('Y-m-d');
        }
        if (empty($data['discount_total'])) {
            $data['discount_total'] = 0;
        }
        $data['invoice_year'] = date('Y', safe_strtotime($this->input->post('invoice_date', TRUE)));
        $data['invoice_month'] = date('Y-m', safe_strtotime($this->input->post('invoice_date', TRUE)));
        $data['due_date'] = date('Y-m-d', safe_strtotime($this->input->post('due_date', TRUE)));
        $data['notes'] = $this->input->post('notes', TRUE);
        $tax['tax_name'] = $this->input->post('total_tax_name', TRUE);
        $tax['total_tax'] = $this->input->post('total_tax', TRUE);
        $data['total_tax'] = json_encode($tax);
        $i_tax = 0;
        if (!empty($tax['total_tax'])) {
            foreach ($tax['total_tax'] as $v_tax) {
                $i_tax += $v_tax;
            }
        }
        $data['tax'] = $i_tax;
        $save_as_draft = $this->input->post('save_as_draft', TRUE);
        if (!empty($save_as_draft)) {
            $data['status'] = 'draft';
        }
        $currency = $this->proposal_model->client_currency_symbol($data['client_id']);
        if (!empty($currency->code)) {
            $curren = $currency->code;
        } else {
            $curren = config_item('default_currency');
        }
        $data['currency'] = $curren;

        $permission = $this->input->post('permission', true);
        if (!empty($permission)) {
            if ($permission == 'everyone') {
                $assigned = 'all';
            } else {
                $assigned_to = $this->proposal_model->array_from_post(array('assigned_to'));
                if (!empty($assigned_to['assigned_to'])) {
                    foreach ($assigned_to['assigned_to'] as $assign_user) {
                        $assigned[$assign_user] = $this->input->post('action_' . $assign_user, true);
                    }
                }
            }
            if (!empty($assigned)) {
                if ($assigned != 'all') {
                    $assigned = json_encode($assigned);
                }
            } else {
                $assigned = 'all';
            }
            $data['permission'] = $assigned;
        } else {
            $this->db->trans_rollback();
            set_message('error', lang('assigned_to') . ' Field is required');
            if (empty($_SERVER['HTTP_REFERER'])) {
                redirect('admin/proposals');
            } else {
                redirect($_SERVER['HTTP_REFERER']);
            }
        }

        // get all client
        $this->proposal_model->_table_name = 'tbl_invoices';
        $this->proposal_model->_primary_key = 'invoices_id';

        $invoice_id = $this->proposal_model->save($data);
        $recuring_frequency = $this->input->post('recuring_frequency', TRUE);

        if (!empty($recuring_frequency) && $recuring_frequency != 'none') {
            $recur_data = $this->proposal_model->array_from_post(array('recur_start_date', 'recur_end_date'));
            $recur_data['recuring_frequency'] = $recuring_frequency;
            $this->get_recuring_frequency($invoice_id, $recur_data); // set recurring
        }
        // save items
        $qty_calculation = config_item('qty_calculation_from_items');
        // save items
        $invoices_to_merge = $this->input->post('invoices_to_merge', TRUE);
        $cancel_merged_invoices = $this->input->post('cancel_merged_invoices', TRUE);
        if (!empty($invoices_to_merge)) {
            foreach ($invoices_to_merge as $inv_id) {
                if (empty($cancel_merged_invoices)) {
                    if (!empty($qty_calculation) && $qty_calculation == 'Yes') {
                        $all_items_info = $this->db->where('invoices_id', $inv_id)->get('tbl_items')->result();
                        if (!empty($all_items_info)) {
                            foreach ($all_items_info as $v_items) {
                                if (!$this->proposal_model->return_items($v_items->saved_items_id, $v_items->quantity, $data['warehouse_id'])) {
                                    $stock_ok = false;
                                    break;
                                }
                            }
                        }
                        if (!$stock_ok) {
                            break;
                        }
                    }
                    $this->db->where('invoices_id', $inv_id);
                    $this->db->delete('tbl_invoices');

                    $this->db->where('invoices_id', $inv_id);
                    $this->db->delete('tbl_items');
                } else {
                    $mdata = array('status' => 'Cancelled');
                    $this->proposal_model->_table_name = 'tbl_invoices';
                    $this->proposal_model->_primary_key = 'invoices_id';
                    $this->proposal_model->save($mdata, $inv_id);
                }
            }
            if (!$stock_ok) {
                $this->db->trans_rollback();
                set_message('error', $stock_error);
                redirect($_SERVER['HTTP_REFERER']);
            }
        }

        $removed_items = $this->input->post('removed_items', TRUE);
        if (!empty($removed_items)) {
            foreach ($removed_items as $r_id) {
                if ($r_id != 'undefined') {
                    if (!empty($qty_calculation) && $qty_calculation == 'Yes') {
                        $itemInfo = get_row('tbl_items', array('items_id' => $r_id));
                        if (!$this->proposal_model->return_items($itemInfo->saved_items_id, $itemInfo->quantity, $data['warehouse_id'])) {
                            $stock_ok = false;
                            break;
                        }
                    }

                    $this->db->where('items_id', $r_id);
                    $this->db->delete('tbl_items');
                }
            }
        }
        if (!$stock_ok) {
            $this->db->trans_rollback();
            set_message('error', $stock_error);
            redirect($_SERVER['HTTP_REFERER']);
        }

        $itemsid = $this->input->post('items_id', TRUE);
        $items_data = $this->input->post('items', true);

        if (!empty($items_data)) {
            $index = 0;
            foreach ($items_data as $items) {
                $items['invoices_id'] = $invoice_id;
                $tax = 0;
                if (!empty($items['taxname'])) {
                    foreach ($items['taxname'] as $tax_name) {
                        $tax_rate = explode("|", $tax_name);
                        $tax += $tax_rate[1];
                    }
                    $items['item_tax_name'] = $items['taxname'];
                    unset($items['taxname']);
                    $items['item_tax_name'] = json_encode($items['item_tax_name']);
                }
                if (empty($items['saved_items_id'])) {
                    $items['saved_items_id'] = 0;
                }
                if (!empty($qty_calculation) && $qty_calculation == 'Yes') {
                    if (!empty($items['saved_items_id']) && $items['saved_items_id'] != 'undefined') {
                        if (!$this->proposal_model->reduce_items($items['saved_items_id'], $items['quantity'], $data['warehouse_id'])) {
                            $stock_ok = false;
                            break;
                        }
                    }
                }
                $price = $items['quantity'] * $items['unit_cost'];
                $items['item_tax_total'] = ($price / 100 * $tax);
                $items['total_cost'] = $price;
                // get all client
                $this->proposal_model->_table_name = 'tbl_items';
                $this->proposal_model->_primary_key = 'items_id';
                $this->proposal_model->save($items);
                $index++;
            }
        }
        if (!$stock_ok || $this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            set_message('error', $stock_error);
            redirect($_SERVER['HTTP_REFERER']);
        }

        $p_data = array('status' => 'accepted', 'convert' => 'Yes', 'convert_module' => 'invoice', 'convert_module_id' => $invoice_id);

        $this->proposal_model->_table_name = 'tbl_proposals';
        $this->proposal_model->_primary_key = 'proposals_id';
        $this->proposal_model->save($p_data, $proposal_id);

        $activity = array(
            'user' => $this->session->userdata('user_id'),
            'module' => 'proposals',
            'module_field_id' => $invoice_id,
            'activity' => 'convert_to_invoice_from_proposal',
            'icon' => 'fa-shopping-cart',
            'link' => 'admin/proposals/index/proposals_details/' . $proposal_id,
            'value1' => $data['reference_no']
        );
        $this->proposal_model->_table_name = 'tbl_activities';
        $this->proposal_model->_primary_key = 'activities_id';
        $this->proposal_model->save($activity);
        $this->db->trans_commit();

        // send notification to client
        if (!empty($data['client_id'])) {
            $client_info = $this->proposal_model->check_by(array('client_id' => $data['client_id']), 'tbl_client');
            if (!empty($client_info->primary_contact)) {
                $notifyUser = array($client_info->primary_contact);
            } else {
                $user_info = $this->proposal_model->check_by(array('company' => $data['client_id']), 'tbl_account_details');
                if (!empty($user_info)) {
                    $notifyUser = array($user_info->user_id);
                }
            }
        }
        if (!empty($notifyUser)) {
            foreach ($notifyUser as $v_user) {
                if ($v_user != $this->session->userdata('user_id')) {
                    add_notification(array(
                        'to_user_id' => $v_user,
                        'icon' => 'shopping-cart',
                        'description' => 'proposal_convert_to_invoice',
                        'link' => 'client/invoice/manage_invoice/invoice_details/' . $invoice_id,
                        'value' => $data['reference_no'],
                    ));
                }
            }
            show_notification($notifyUser);
        }
        // messages for user
        $type = "success";
        $message = lang('convert_to_invoice') . ' ' . lang('successfully');
        set_message($type, $message);
        if ($this->input->is_ajax_request()) {
            echo json_encode(array(
                'status' => 'success',
                'message' => $message,
                'id' => $invoice_id,
                'reference_no' => $data['reference_no'],
                'url' => 'admin/proposals/index/proposals_details/' . $proposal_id,
                'reload_page' => true,
            ));
            return;
        }
        redirect('admin/proposals/index/proposals_details/' . $proposal_id);
    }

    function get_recuring_frequency($invoices_id, $recur_data)
    {
        $recur_days = $this->get_calculate_recurring_days($recur_data['recuring_frequency']);
        $due_date = $this->proposal_model->get_table_field('tbl_invoices', array('invoices_id' => $invoices_id), 'due_date');

        $next_date = date("Y-m-d", safe_strtotime($due_date . "+ " . $recur_days . " days"));

        if ($recur_data['recur_end_date'] == '') {
            $recur_end_date = '0000-00-00';
        } else {
            $recur_end_date = date('Y-m-d', safe_strtotime($recur_data['recur_end_date']));
        }
        $update_invoice = array(
            'recurring' => 'Yes',
            'recuring_frequency' => $recur_days,
            'recur_frequency' => $recur_data['recuring_frequency'],
            'recur_start_date' => date('Y-m-d', safe_strtotime($recur_data['recur_start_date'])),
            'recur_end_date' => $recur_end_date,
            'recur_next_date' => $next_date
        );
        $this->proposal_model->_table_name = 'tbl_invoices';
        $this->proposal_model->_primary_key = 'invoices_id';
        $this->proposal_model->save($update_invoice, $invoices_id);
        return TRUE;
    }

    function get_calculate_recurring_days($recuring_frequency)
    {
        switch ($recuring_frequency) {
            case '7D':
                return 7;
                break;
            case '1M':
                return 31;
                break;
            case '3M':
                return 90;
                break;
            case '6M':
                return 182;
                break;
            case '1Y':
                return 365;
                break;
        }
    }

    public function converted_to_estimate($proposal_id)
    {
        $data = $this->proposal_model->array_from_post(array('reference_no', 'client_id', 'project_id', 'discount_type', 'discount_percent', 'user_id', 'adjustment', 'discount_total', 'show_quantity_as'));
        $this->db->trans_begin();
        if (!empty($data['reference_no']) && $this->db->where('reference_no', $data['reference_no'])->count_all_results('tbl_estimates') > 0) {
            $data['reference_no'] = $this->proposal_model->generate_estimate_number();
        }

        $data['client_visible'] = ($this->input->post('client_visible') == 'Yes') ? 'Yes' : 'No';
        $data['estimate_date'] = date('Y-m-d', safe_strtotime($this->input->post('estimate_date', TRUE)));
        if (empty($data['estimate_date'])) {
            $data['estimate_date'] = date('Y-m-d');
        }
        if (empty($data['discount_total'])) {
            $data['discount_total'] = 0;
        }
        $data['estimate_year'] = date('Y', safe_strtotime($this->input->post('estimate_date', TRUE)));
        $data['estimate_month'] = date('Y-m', safe_strtotime($this->input->post('estimate_date', TRUE)));
        $data['due_date'] = date('Y-m-d', safe_strtotime($this->input->post('due_date', TRUE)));
        $data['notes'] = $this->input->post('notes', TRUE);
        $tax['tax_name'] = $this->input->post('total_tax_name', TRUE);
        $tax['total_tax'] = $this->input->post('total_tax', TRUE);
        $data['total_tax'] = json_encode($tax);
        $i_tax = 0;
        if (!empty($tax['total_tax'])) {
            foreach ($tax['total_tax'] as $v_tax) {
                $i_tax += $v_tax;
            }
        }
        $data['tax'] = $i_tax;
        $save_as_draft = $this->input->post('status', TRUE);
        if (!empty($save_as_draft)) {
            $data['status'] = $save_as_draft;
        } else {
            $data['status'] = 'pending';
        }
        $currency = $this->proposal_model->client_currency_symbol($data['client_id']);
        if (!empty($currency->code)) {
            $curren = $currency->code;
        } else {
            $curren = config_item('default_currency');
        }
        $data['currency'] = $curren;

        $permission = $this->input->post('permission', true);
        if (!empty($permission)) {
            if ($permission == 'everyone') {
                $assigned = 'all';
            } else {
                $assigned_to = $this->proposal_model->array_from_post(array('assigned_to'));
                if (!empty($assigned_to['assigned_to'])) {
                    foreach ($assigned_to['assigned_to'] as $assign_user) {
                        $assigned[$assign_user] = $this->input->post('action_' . $assign_user, true);
                    }
                }
            }
            if (!empty($assigned)) {
                if ($assigned != 'all') {
                    $assigned = json_encode($assigned);
                }
            } else {
                $assigned = 'all';
            }
            $data['permission'] = $assigned;
        } else {
            set_message('error', lang('assigned_to') . ' Field is required');
            if (empty($_SERVER['HTTP_REFERER'])) {
                redirect('admin/proposals');
            } else {
                redirect($_SERVER['HTTP_REFERER']);
            }
        }
        // get all client
        $this->proposal_model->_table_name = 'tbl_estimates';
        $this->proposal_model->_primary_key = 'estimates_id';
        if (!empty($id)) {
            $estimates_id = $id;
            $this->proposal_model->save($data, $id);
        } else {
            $estimates_id = $this->proposal_model->save($data);
        }
        // save items
        $invoices_to_merge = $this->input->post('invoices_to_merge', TRUE);
        $cancel_merged_invoices = $this->input->post('cancel_merged_estimate', TRUE);
        if (!empty($invoices_to_merge)) {
            foreach ($invoices_to_merge as $inv_id) {
                if (empty($cancel_merged_invoices)) {
                    $this->db->where('estimates_id', $inv_id);
                    $this->db->delete('tbl_estimates');

                    $this->db->where('estimate_items_id', $inv_id);
                    $this->db->delete('tbl_estimate_items');
                } else {
                    $mdata = array('status' => 'cancelled');
                    $this->proposal_model->_table_name = 'tbl_estimates';
                    $this->proposal_model->_primary_key = 'estimates_id';
                    $this->proposal_model->save($mdata, $inv_id);
                }
            }
        }

        $removed_items = $this->input->post('removed_items', TRUE);
        if (!empty($removed_items)) {
            foreach ($removed_items as $r_id) {
                if ($r_id != 'undefined') {
                    $this->db->where('estimate_items_id', $r_id);
                    $this->db->delete('tbl_estimate_items');
                }
            }
        }

        $itemsid = $this->input->post('estimate_items_id', TRUE);
        $items_data = $this->input->post('items', true);

        if (!empty($items_data)) {
            $index = 0;
            foreach ($items_data as $items) {
                $items['estimates_id'] = $estimates_id;
                unset($items['items_id']);
                if (!empty($items['taxname'])) {
                    $tax = 0;
                    foreach ($items['taxname'] as $tax_name) {
                        $tax_rate = explode("|", $tax_name);
                        $tax += $tax_rate[1];
                    }
                    $price = $items['quantity'] * $items['unit_cost'];
                    $items['item_tax_total'] = ($price / 100 * $tax);
                    $items['total_cost'] = $price;

                    $items['item_tax_name'] = $items['taxname'];
                    unset($items['taxname']);
                    $items['item_tax_name'] = json_encode($items['item_tax_name']);
                }
                // get all client
                $this->proposal_model->_table_name = 'tbl_estimate_items';
                $this->proposal_model->_primary_key = 'estimate_items_id';
                if (!empty($itemsid[$index])) {
                    $items_id = $itemsid[$index];
                    $this->proposal_model->save($items, $items_id);
                } else {
                    $items_id = $this->proposal_model->save($items);
                }
                $index++;
            }
        }
        $p_data = array('status' => 'accepted', 'convert' => 'Yes', 'convert_module' => 'estimate', 'convert_module_id' => $estimates_id);
        $this->proposal_model->_table_name = 'tbl_proposals';
        $this->proposal_model->_primary_key = 'proposals_id';
        $this->proposal_model->save($p_data, $proposal_id);

        $activity = array(
            'user' => $this->session->userdata('user_id'),
            'module' => 'proposals',
            'module_field_id' => $estimates_id,
            'activity' => 'convert_to_estimate_from_proposal',
            'icon' => 'fa-shopping-cart',
            'link' => 'admin/proposals/index/proposals_details/' . $proposal_id,
            'value1' => $data['reference_no']
        );
        $this->proposal_model->_table_name = 'tbl_activities';
        $this->proposal_model->_primary_key = 'activities_id';
        $this->proposal_model->save($activity);
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            set_message('error', lang('please_try_again'));
            redirect($_SERVER['HTTP_REFERER']);
        }
        $this->db->trans_commit();

        // send notification to client
        if (!empty($data['client_id'])) {
            $client_info = $this->proposal_model->check_by(array('client_id' => $data['client_id']), 'tbl_client');
            if (!empty($client_info->primary_contact)) {
                $notifyUser = array($client_info->primary_contact);
            } else {
                $user_info = $this->proposal_model->check_by(array('company' => $data['client_id']), 'tbl_account_details');
                if (!empty($user_info)) {
                    $notifyUser = array($user_info->user_id);
                }
            }
        }
        if (!empty($notifyUser)) {
            foreach ($notifyUser as $v_user) {
                if ($v_user != $this->session->userdata('user_id')) {
                    add_notification(array(
                        'to_user_id' => $v_user,
                        'icon' => 'shopping-cart',
                        'description' => 'proposal_convert_to_estimate',
                        'link' => 'client/estimates/index/estimates_details/' . $estimates_id,
                        'value' => $data['reference_no'],
                    ));
                }
            }
            show_notification($notifyUser);
        }
        // messages for user
        $type = "success";
        $message = lang('convert_to_estimate') . ' ' . lang('successfully');
        set_message($type, $message);
        if ($this->input->is_ajax_request()) {
            echo json_encode(array(
                'status' => 'success',
                'message' => $message,
                'id' => $estimates_id,
                'reference_no' => $data['reference_no'],
                'url' => 'admin/proposals/index/proposals_details/' . $proposal_id,
                'reload_page' => true,
            ));
            return;
        }
        redirect('admin/proposals/index/proposals_details/' . $proposal_id);
    }
}
