<?php

class Proposal_Model extends MY_Model
{

    public $_table_name;
    public $_order_by;
    public $_primary_key;

    function proposal_calculation($proposal_value, $proposals_id)
    {
        switch ($proposal_value) {
            case 'proposal_cost':
                return $this->get_proposal_cost($proposals_id);
                break;
            case 'tax':
                return $this->get_proposal_tax_amount($proposals_id);
                break;
            case 'discount':
                return $this->get_proposal_discount($proposals_id);
                break;
            case 'proposal_amount':
                return $this->get_proposal_amount($proposals_id);
                break;
            case 'total':
                return $this->get_total_proposal_amount($proposals_id);
                break;
        }
    }




    function get_proposal_cost($proposals_id)
    {
        $this->db->select_sum('total_cost');
        $this->db->where('proposals_id', $proposals_id);
        $this->db->from('tbl_proposals_items');
        $query_result = $this->db->get();
        $cost = $query_result->row();
        if (!empty($cost->total_cost)) {
            $result = $cost->total_cost;
        } else {
            $result = '0';
        }
        return $result;
    }

    function get_proposal_tax_amount($proposals_id)
    {
        $invoice_info = $this->check_by(array('proposals_id' => $proposals_id), 'tbl_proposals');
        if (empty($invoice_info) || !isset($invoice_info->total_tax) || $invoice_info->total_tax === '' || $invoice_info->total_tax === null) {
            return 0;
        }

        $tax = 0;
        $raw_tax = $invoice_info->total_tax;
        $tax_info = json_decode($raw_tax, true);

        if (json_last_error() === JSON_ERROR_NONE) {
            if (isset($tax_info['total_tax'])) {
                $total_tax = $tax_info['total_tax'];
                if (is_array($total_tax)) {
                    foreach ($total_tax as $v_tax_info) {
                        $tax += (float) $v_tax_info;
                    }
                } elseif (is_numeric($total_tax)) {
                    $tax += (float) $total_tax;
                }
            } elseif (is_array($tax_info)) {
                foreach ($tax_info as $v_tax_info) {
                    $tax += $v_tax_info;
                }
            }
        } elseif (is_numeric($raw_tax)) {
            $tax = (float) $raw_tax;
        }

        return $tax;
    }

    function get_proposal_discount($proposals_id)
    {
        $invoice_info = $this->check_by(array('proposals_id' => $proposals_id), 'tbl_proposals');
        if (!empty($invoice_info)) {
            return $invoice_info->discount_total;
        } else {
            return '0';
        }
    }

    function get_proposal_amount($proposals_id)
    {

        $tax = $this->get_proposal_tax_amount($proposals_id);
        $discount = $this->get_proposal_discount($proposals_id);
        $proposal_cost = $this->get_proposal_cost($proposals_id);
        return (($proposal_cost - $discount) + $tax);
    }

    function get_total_proposal_amount($proposals_id)
    {
        $invoice_info = $this->check_by(array('proposals_id' => $proposals_id), 'tbl_proposals');
        $tax = $this->get_proposal_tax_amount($proposals_id);
        $discount = $this->get_proposal_discount($proposals_id);
        $proposal_cost = $this->get_proposal_cost($proposals_id);
        return (($proposal_cost - $discount) + $tax + $invoice_info->adjustment);
    }

    function ordered_items_by_id($id, $json = null)
    {
        $rows = $this->db->where('proposals_id', $id)->order_by('order', 'asc')->get('tbl_proposals_items')->result();
        if (!empty($json)) {
            if (!empty($rows)) {
                foreach ($rows as $row) {
                    $row->items_id = $row->proposals_items_id;
                    $row->qty = $row->quantity;
                    $row->rate = $row->unit_cost;
                    $row->cost_price = $row->unit_cost;
                    $row->new_itmes_id = $row->saved_items_id;
                    $row->taxname = json_decode($row->item_tax_name);
                    $pr[] = $row;
                }
                return json_encode($pr);
            }
        } else {
            return $rows;
        }
    }


    public function check_for_merge_invoice($client_id, $current_proposal)
    {

        $proposal_info = $this->db->where('client_id', $client_id)->get('tbl_proposals')->result();

        foreach ($proposal_info as $v_proposal) {
            if ($v_proposal->proposals_id != $current_proposal) {
                if ($v_proposal->status == 'Pending' || $v_proposal->status == 'draft') {
                    $proposal[] = $v_proposal;
                }
            }
        }
        if (!empty($proposal)) {
            return $proposal;
        } else {
            return array();
        }
    }

    public function get_invoice_filter()
    {

        $this->db->select('proposal_year');
        $this->db->group_by('proposal_year');
        $result = $this->db->get('tbl_proposals')->result();

        $statuses = array(
            array(
                'id' => 1,
                'value' => 'draft',
                'name' => lang('draft'),
                'order' => 1,
            ), array(
                'id' => 1,
                'value' => 'expired',
                'name' => lang('expired'),
                'order' => 1,
            ), array(
                'id' => 1,
                'value' => 'open',
                'name' => lang('open'),
                'order' => 1,
            ),
            array(
                'id' => 4,
                'value' => 'declined',
                'name' => lang('declined'),
                'order' => 4,
            ),
            array(
                'id' => 4,
                'value' => 'accepted',
                'name' => lang('accepted'),
                'order' => 4,
            ),
            array(
                'id' => 4,
                'value' => 'last_month',
                'name' => lang('last_month'),
                'order' => 4,
            ),
            array(
                'id' => 4,
                'value' => 'this_months',
                'name' => lang('this_months'),
                'order' => 4,
            )
        );
        if (!empty($result)) {
            foreach ($result as $v_year) {
                $test = array(
                    'id' => 1,
                    'value' => '_' . $v_year->proposal_year,
                    'name' => $v_year->proposal_year,
                    'order' => 1
                );
                if (!empty($test)) {
                    array_push($statuses, $test);
                }
            }
        }
        return $statuses;
    }

    public function get_proposals($filterBy = null)
    {
        $all_invoice = $this->get_permission('tbl_proposals');

        if (empty($filterBy) || !empty($filterBy) && $filterBy == 'all') {
            return $all_invoice;
        } else {
            if (!empty($all_invoice)) {
                $all_invoice = array_reverse($all_invoice);
                foreach ($all_invoice as $v_invoices) {

                    if ($filterBy == 'last_month' || $filterBy == 'this_months') {
                        if ($filterBy == 'last_month') {
                            $month = date('Y-m', safe_strtotime('-1 months'));
                        } else {
                            $month = date('Y-m');
                        }
                        if (safe_strtotime($v_invoices->proposal_month) == safe_strtotime($month)) {
                            $invoice[] = $v_invoices;
                        }
                    } else if ($filterBy == 'expired') {
                        if (safe_strtotime($v_invoices->due_date) < safe_strtotime(date('Y-m-d')) && $v_invoices->status == ('pending') || safe_strtotime($v_invoices->due_date) < safe_strtotime(date('Y-m-d')) && $v_invoices->status == ('draft')) {
                            $invoice[] = $v_invoices;
                        }
                    } else if ($filterBy == $v_invoices->status) {
                        $invoice[] = $v_invoices;
                    } else if (strstr($filterBy, '_')) {
                        $year = str_replace('_', '', $filterBy);
                        if (safe_strtotime($v_invoices->proposal_year) == safe_strtotime($year)) {
                            $invoice[] = $v_invoices;
                        }
                    }
                }
            }
        }
        if (!empty($invoice)) {
            return $invoice;
        } else {
            return array();
        }
    }

    protected function normalize_proposal_sidebar_row($proposal)
    {
        if (empty($proposal)) {
            return null;
        }

        $proposal = clone $proposal;
        $proposal->client_name = '-';
        $proposal->currency_symbol = default_currency();
        $proposal->total_amount = (float) $this->proposal_calculation('total', $proposal->proposals_id);
        $proposal->status_label = lang($proposal->status);
        $proposal->status_badge = 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300';
        $proposal->is_overdue = false;
        $proposal->overdue_label = '';

        if ($proposal->module == 'client') {
            $client_info = $this->check_by(array('client_id' => $proposal->module_id), 'tbl_client');
            if (!empty($client_info)) {
                $proposal->client_name = $client_info->name;
            }
            $proposal->currency_symbol = client_currency($proposal->module_id);
            $proposal->module_label = lang('client');
        } elseif ($proposal->module == 'leads') {
            $lead_info = $this->check_by(array('leads_id' => $proposal->module_id), 'tbl_leads');
            if (!empty($lead_info)) {
                $proposal->client_name = $lead_info->lead_name;
            }
            $proposal->module_label = lang('leads');
        } else {
            $proposal->module_label = '-';
        }

        if ($proposal->convert == 'Yes') {
            if ($proposal->convert_module == 'estimate') {
                $proposal->status_label = strtoupper(lang('estimated'));
            } else {
                $proposal->status_label = strtoupper(lang('invoiced'));
            }
            $proposal->status_badge = 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300';
        } elseif ($proposal->emailed == 'Yes') {
            $proposal->status_label = strtoupper(lang('sent'));
            $proposal->status_badge = 'bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300';
        } else {
            $status_key = strtolower((string) $proposal->status);
            if ($status_key === 'pending') {
                $proposal->status_badge = 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300';
            } elseif ($status_key === 'accepted') {
                $proposal->status_badge = 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300';
            } elseif ($status_key === 'declined' || $status_key === 'cancelled') {
                $proposal->status_badge = 'bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300';
            }
        }

        if ((safe_strtotime($proposal->due_date) < safe_strtotime(date('Y-m-d'))) && ($proposal->status == 'pending' || $proposal->status == 'draft')) {
            $proposal->is_overdue = true;
            $proposal->overdue_label = lang('expired');
        }

        return $proposal;
    }

    protected function proposal_sidebar_matches_search($proposal, $search = '')
    {
        $search = trim(mb_strtolower((string) $search));
        if ($search === '') {
            return true;
        }

        $haystack = array(
            $proposal->reference_no,
            $proposal->client_name,
            $proposal->module_label,
            $proposal->status_label,
            display_date($proposal->proposal_date),
            display_date($proposal->due_date),
            number_format((float) $proposal->total_amount, 2, '.', ''),
            (string) $proposal->proposals_id,
        );
        $haystack = mb_strtolower(trim(implode(' ', array_filter($haystack))));

        return strpos($haystack, $search) !== false;
    }

    public function count_proposal_sidebar($search = '')
    {
        $all_proposals = $this->get_permission('tbl_proposals', null, null, FALSE, array('proposals_id' => 'desc'));
        if (empty($all_proposals)) {
            return 0;
        }

        $count = 0;
        foreach ($all_proposals as $proposal) {
            $proposal_row = $this->normalize_proposal_sidebar_row($proposal);
            if (!empty($proposal_row) && $this->proposal_sidebar_matches_search($proposal_row, $search)) {
                $count++;
            }
        }

        return $count;
    }

    public function get_proposal_sidebar_page($limit = 12, $offset = 0, $search = '')
    {
        $all_proposals = $this->get_permission('tbl_proposals', null, null, FALSE, array('proposals_id' => 'desc'));
        if (empty($all_proposals)) {
            return array();
        }

        $rows = array();
        foreach ($all_proposals as $proposal) {
            $proposal_row = $this->normalize_proposal_sidebar_row($proposal);
            if (!empty($proposal_row) && $this->proposal_sidebar_matches_search($proposal_row, $search)) {
                $rows[] = $proposal_row;
            }
        }

        return array_slice($rows, (int) $offset, (int) $limit);
    }

    public function get_proposal_sidebar_proposal($proposal_id)
    {
        $proposal = $this->check_by(array('proposals_id' => $proposal_id), 'tbl_proposals');
        if (empty($proposal)) {
            return null;
        }

        return $this->normalize_proposal_sidebar_row($proposal);
    }

    public function count_proposal_activities($proposal_id)
    {
        return (int) $this->db
            ->where(array(
                'module' => 'proposals',
                'module_field_id' => (int) $proposal_id,
            ))
            ->count_all_results('tbl_activities');
    }

    public function get_proposal_activity_page($proposal_id, $limit = 20, $offset = 0)
    {
        return $this->db
            ->select('tbl_activities.*, tbl_account_details.fullname AS actor_name, tbl_account_details.user_id AS actor_user_id')
            ->from('tbl_activities')
            ->join('tbl_account_details', 'tbl_account_details.user_id = tbl_activities.user', 'left')
            ->where(array(
                'tbl_activities.module' => 'proposals',
                'tbl_activities.module_field_id' => (int) $proposal_id,
            ))
            ->order_by('tbl_activities.activity_date', 'DESC')
            ->limit((int) $limit, (int) $offset)
            ->get()
            ->result();
    }

    public function get_client_proposals($filterBy = null)
    {
        $all_invoice = get_result('tbl_proposals', array('status !=' => 'draft', 'module' => 'client', 'module_id' => $this->session->userdata('client_id')));
        if (empty($filterBy) || !empty($filterBy) && $filterBy == 'all') {
            return $all_invoice;
        } else {
            if (!empty($all_invoice)) {
                $all_invoice = array_reverse($all_invoice);
                foreach ($all_invoice as $v_invoices) {

                    if ($filterBy == 'last_month' || $filterBy == 'this_months') {
                        if ($filterBy == 'last_month') {
                            $month = date('Y-m', safe_strtotime('-1 months'));
                        } else {
                            $month = date('Y-m');
                        }
                        if (safe_strtotime($v_invoices->proposal_month) == safe_strtotime($month)) {
                            $invoice[] = $v_invoices;
                        }
                    } else if ($filterBy == 'expired') {
                        if (safe_strtotime($v_invoices->due_date) < safe_strtotime(date('Y-m-d')) && $v_invoices->status == ('pending') || safe_strtotime($v_invoices->due_date) < safe_strtotime(date('Y-m-d')) && $v_invoices->status == ('draft')) {
                            $invoice[] = $v_invoices;
                        }
                    } else if ($filterBy == $v_invoices->status) {
                        $invoice[] = $v_invoices;
                    } else if (strstr($filterBy, '_')) {
                        $year = str_replace('_', '', $filterBy);
                        if (safe_strtotime($v_invoices->proposal_year) == safe_strtotime($year)) {
                            $invoice[] = $v_invoices;
                        }
                    }
                }
            }
        }
        if (!empty($invoice)) {
            return $invoice;
        } else {
            return array();
        }
    }

    public function get_proposals_report($filterBy = null, $range = null)
    {
        if (!empty($filterBy) && is_numeric($filterBy)) {
            $proposals = $this->db->where(array('module' => 'client', 'module_id' => $filterBy))->get('tbl_proposals')->result();
        } else {
            $all_proposals = $this->get_permission('tbl_proposals');
        }
        if (empty($filterBy) || !empty($filterBy) && $filterBy == 'all') {
            $proposals = $all_proposals;
        } else {
            if (!empty($all_proposals)) {
                $all_proposals = array_reverse($all_proposals);
                foreach ($all_proposals as $v_proposals) {
                    if ($filterBy == 'last_month' || $filterBy == 'this_months') {
                        if ($filterBy == 'last_month') {
                            $month = date('Y-m', safe_strtotime('-1 months'));
                        } else {
                            $month = date('Y-m');
                        }
                        if (safe_strtotime($v_proposals->proposal_month) == safe_strtotime($month)) {
                            $proposals[] = $v_proposals;
                        }
                    } else if ($filterBy == 'expired') {
                        if (safe_strtotime($v_proposals->due_date) < safe_strtotime(date('Y-m-d')) && $v_proposals->status == ('pending') || safe_strtotime($v_proposals->due_date) < safe_strtotime(date('Y-m-d')) && $v_proposals->status == ('draft')) {
                            $proposals[] = $v_proposals;
                        }
                    } else if ($filterBy == $v_proposals->status) {
                        $proposals[] = $v_proposals;
                    } else if (strstr($filterBy, '_')) {
                        $year = str_replace('_', '', $filterBy);
                        if (safe_strtotime($v_proposals->proposal_year) == safe_strtotime($year)) {
                            $proposals[] = $v_proposals;
                        }
                    }
                }
            }
        }
        if (!empty($proposals)) {
            $proposal_info = array();
            if (!empty($range[0])) {
                foreach ($proposals as $v_proposal) {
                    if ($v_proposal->proposal_date >= $range[0] && $v_proposal->proposal_date <= $range[1]) {
                        array_push($proposal_info, $v_proposal);
                    }
                }
                return $proposal_info;
            } else {
                return $proposals;
            }
        } else {
            return array();
        }
    }
}
