<?php
namespace App\Controllers\Client;
use App\Controllers\BaseController;
use App\Core\Service\Logger;
use App\Config\Main;
use App\Model\FxModel;
use App\Model\ReportModel;

class ReportController extends BaseController
{
    private $FxModel;
    private $ReportModel;
    private $colors = [
        '#008FFB', '#FFC107', '#FF9800', '#4CAF50', '#2196F3',
        '#9C27B0', '#03A9F4', '#8BC34A', '#FF69B4', '#3F51B5',
        '#009688', '#FFA07A', '#F44336', '#8E24AA', '#795548',
        '#9E9E9E', '#F48FB1', '#7E57C2', '#64B5F6', '#4DB6AC'
    ];
    public function __construct() {
        parent::__construct();
        $this->FxModel = new FxModel();
        $this->ReportModel = new ReportModel();
    }

    public function getOrderReport() {
        try {
            $status_list = $this->FxModel->getOrderStatusListOwned($this->user_data->comp_id, $this->user_data);                
            if(empty($status_list['status'])) {
                throw new \Exception($status_list['error']);
            }
            $branch_list = $this->FxModel->getBranchRightsOwned($this->user_data->comp_id, $this->user_data);                
            if(empty($branch_list['status'])) {
                throw new \Exception($branch_list['error']);
            }
            $branches = !empty($branch_list['data'])? explode(",", $branch_list['data']) : [];

            $wharr = [];
            $report_by = '';
            if(!empty($this->input['search'])) {
                foreach($this->input['search'] as $field=>$value) {
                    if($field == 'order_status') {
                        if(!empty($value)) {
                            if($value == 1) { //ALL
                                if($this->user_data->master_type != 1) {
                                    if(!empty($status_list['data']['owned'])) {
                                    $wharr['current_order_status'] = $status_list['data']['owned'];
                                    }
                                }
                            } else if($value == 2) { //Pending
                                if(!empty($status_list['data']['completed'])) {
                                    $wharr['order_status_not_in'] = $status_list['data']['completed'];
                                }
                            } else if($value == 3) { //Completed
                                if(!empty($status_list['data']['completed'])) {
                                    $wharr['current_order_status'] = $status_list['data']['completed'];
                                }
                            }
                        }
                    } else if($field == 'assign_type') {
                        if(!empty($value)) {
                            if($value == 2) {
                                $wharr['last_allocate_uid'] = 0;
                            } else if($value == 3) {
                                $wharr['last_allocate_uid_null'] = NULL;
                            }
                        }
                    } else if($field == 'branch_id') {
                        if(!empty($value)) {
                            if($this->user_data->master_type != 1 && in_array($value, $branches)) {
                                $wharr['branch_id'] = $value;
                            }
                        } else if($this->user_data->master_type != 1 && !empty($branch_list['data'])) {
                            $wharr['branch_id_in'] = $branch_list['data'];
                        }
                    } else if($field == 'report_by') {
                        $report_by = $value;
                    } else {
                        $wharr[$field] = $value;
                    }
                }    
            }
            
            $whstring = $this->FxModel->whereString(
                $wharr,
                array('*'=>'t.', 'customer_id' => 'o.', 'mobile_number' => 'c.', 'address_city_id' => 'a.', 'address_pincode' => 'a.', 'address_state_id' => 'a.'),
                array(
                    'order_status_not_in'=>'NOT IN', 
                    'order_status_in'=>'IN',
                    'last_allocate_uid_null'=>'ISNULL',
                    'last_allocate_uid'=>'GT',
                    'branch_id_in'=>'IN',
                    'customer_order_id' => 'LIKE', 'mobile_number' => 'LIKE', 'from_date' => 'DGTE_F', 'to_date' => 'DLTE_L', 'dis_from_date' => 'DGTE_F', 'dis_to_date' => 'DLTE_L', 'inv_from_date' => 'DGTE_F', 'inv_to_date' => 'DLTE_L', 'rto_from_date' => 'DGTE_F', 'rto_to_date' => 'DLTE_L',
                    'delivery_from_date' => 'DGTE_F', 'delivery_to_date' => 'DLTE_L',
                    'payment_from_date' => 'DGTE_F', 'payment_to_date' => 'DLTE_L'
                ), 
                array(
                    'order_status_in'=>'current_order_status', 
                    'order_status_not_in'=>'current_order_status',
                    'last_allocate_uid_null'=>'last_allocate_uid',
                    'branch_id_in'=>'branch_id',
                    'from_date' => 'booking_time', 'to_date' => 'booking_time', 'dis_from_date' => 'dispatch_date', 'dis_to_date' => 'dispatch_date', 'inv_from_date' => 'invoice_date', 'inv_to_date' => 'invoice_date', 'rto_from_date' => 'rto_date', 'rto_to_date' => 'rto_date',
                    'payment_from_date' => 'payment_date', 'payment_to_date' => 'payment_date',
                    'delivery_from_date' => 'delivery_date', 'delivery_to_date' => 'delivery_date'
                )
            );
            if($this->user_data->master_type != 1) {
                $chrs = $this->FxModel->getChildUsers($this->user_data->id);                
                if(empty($chrs['status'])) {
                    throw new \Exception($chrs['error']);
                }
                $whstring .= ' AND (`last_allocate_uid` IS NULL OR `last_allocate_uid` = '.$this->user_data->id.')  AND `order_assign_type` = 0 and `order_booked_by_id` IN ('.$chrs['data'].')';
            }
            $page_no = isset($this->input['page_no']) && is_numeric($this->input['page_no']) ? (int)$this->input['page_no'] : 1;
            $limit = isset($this->input['limit']) && is_numeric($this->input['limit']) ? (int)$this->input['limit'] : 10;

            $sortBy = $this->input['sort_by'] ?? '';
            if ($sortBy) {
                $sort_type = $this->input['sort_type'] ?? 'ASC';
                $sortBy = $sortBy . ' ' . strtoupper($sort_type);
            }
            $dbrs = $this->ReportModel->getOrderListForReport($this->user_data->comp_id, $whstring, $page_no, $limit, $sortBy, $report_by);
            if(empty($dbrs['status'])) {
                throw new \Exception($dbrs['error']);
            }
            $retdata = [];
            $retdata['record'] =  $dbrs['data'];
            
            if($report_by == 'order_wise') {
                if(!empty($dbrs['data'])) {
                    $order_id_arr = array_reduce($dbrs['data'], function ($carry, $order) {
                        return array_merge($carry, [$order['id']]) ;
                    }, []);
                    $order_id_str = implode(",", $order_id_arr);
                    $dbitemrs = $this->ReportModel->getItemListForOrderReport($this->user_data->comp_id, "order_id IN(".$order_id_str.")");
                    if(empty($dbitemrs['status'])) {
                        throw new \Exception($dbitemrs['error']);
                    }
                    $retdata['order_item_list'] = [];
                    foreach($dbitemrs['data'] as $row) {
                        $retdata['order_item_list'][$row['order_id']][] = $row;
                    }
                }
            } else if ($report_by == 'branch_order' || $report_by == 'branch_item_wise') {
                $branchwr = !empty($branches) ? "branch_id IN(".$branches.")" : "";
                $dbrnchrs = $this->FxModel->getBranchList($this->user_data->comp_id, $branchwr);
                if(empty($dbrnchrs['status'])) {
                    throw new \Exception($dbrnchrs['error']);
                }
                $retdata['branch_list'] = [];
                foreach($dbrnchrs['data'] as $row) {
                    $retdata['branch_list'][$row['branch_id']][] = $row;
                }
                $retdata['record'] = [];
                foreach($dbrs['data'] as $data) {
                    $retdata['record'][$data['branch_id']] = $data;
                }
            } else if ($report_by == 'item_wise') {
                $retdata['item_array'] = [];
                $retdata['record'] = [];

                foreach($dbrs['data'] as $value) {
                    $retdata['item_array'][$value['item_id']] = array('item_id' => $value['item_id'], 'item_name' => $value['item_name']);
                    $retdata['record'][$value['item_id']][] = $value;
                }
            } else if ($report_by == 'customer_wise') {
                $retdata['customer_array'] = [];
                $retdata['record'] = [];
                foreach($dbrs['data'] as $value) {
                    $retdata['customer_array'][$value['customer_id']] = array('customer_id' => $value['customer_id'], 'customer_name' => $value['customer_name']);
                    $retdata['record'][$value['customer_id']][] = $value;
                }
            } else if ($report_by == 'agent_wise') {
                $retdata['agent_array'] = [];
                $retdata['record'] = [];
                foreach($dbrs['data'] as $value) {
                    $retdata['agent_array'][$value['order_booked_by_id']] = array('agent_id' => $value['order_booked_by_id'], 'agent_name' => $value['order_booked_by_name']);
                    $retdata['record'][$value['order_booked_by_id']][] = $value;
                }
            } else if($report_by == 'logistics_wise') { 
                $retdata['courier_array'] = [];
                $retdata['record'] = [];
                foreach($dbrs['data'] as $value) {
                    $retdata['courier_array'][$value['courier_id']] = array('courier_id' => $value['courier_id'], 'courier_name' => $value['courier_name']);
                    $retdata['record'][$value['courier_id']][] = $value;
                }
            }   

            $this->sendResponse([
                'code' => 200,
                'message' => 'Data fetched successfully',
                'data' => $retdata,
                'count' => $dbrs['count'],
                'page' => $dbrs['page'],
                'page_limit' => $dbrs['page_limit']
            ]);
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => "Something went wrong while getting report", 'data' => $e->getMessage()));
        }
    }

    function getGstReport() {
        try {
            $branch_list = $this->FxModel->getBranchRightsOwned($this->user_data->comp_id, $this->user_data);                
            if(empty($branch_list['status'])) {
                throw new \Exception($branch_list['error']);
            }
            $branches = !empty($branch_list['data'])? explode(",", $branch_list['data']) : [];

            $wharr = [];
            $report_by = '';

            if(!empty($this->input['search'])) {
                foreach($this->input['search'] as $field=>$value) {
                    if($field == 'branch_id') {
                        if(!empty($value)) {
                            if($this->user_data->master_type != 1 && in_array($value, $branches)) {
                                $wharr['branch_id'] = $value;
                            }
                        } else if($this->user_data->master_type != 1 && !empty($branch_list['data'])) {
                            $wharr['branch_id_in'] = $branch_list['data'];
                        }
                    } else if($field == 'report_by') {
                        $report_by = strtolower($value);
                    } else {
                        $wharr[$field] = $value;
                    }
                }    
            }
            $whstring = $this->FxModel->whereString(
                $wharr,
                array('*' => 't.', 'customer_id' => 'o.', 'mobile_number' => 'c.', 'address_city_id' => 'a.', 'address_pincode' => 'a.', 'address_state_id' => 'a.'),
                array('branch_id_in'=>'IN','customer_order_id' => 'LIKE', 'mobile_number' => 'LIKE', 'from_date' => 'DGTE_F', 'to_date' => 'DLTE_L', 'inv_from_date' => 'DGTE_F', 'inv_to_date' => 'DLTE_L', 'rto_from_date' => 'DGTE_F', 'rto_to_date' => 'DLTE_L',
                    'delivery_from_date' => 'DGTE_F', 'delivery_to_date' => 'DLTE_L','payment_from_date' => 'DGTE_F', 'payment_to_date' => 'DLTE_L'
                ), 
                array('branch_id_in'=>'branch_id','from_date' => 'booking_time', 'to_date' => 'booking_time', 'inv_from_date' => 'invoice_date', 'inv_to_date' => 'invoice_date', 'rto_from_date' => 'rto_date', 'rto_to_date' => 'rto_date',
                    'payment_from_date' => 'payment_date', 'payment_to_date' => 'payment_date','delivery_from_date' => 'delivery_date', 'delivery_to_date' => 'delivery_date'
                )
            );
            $page_no = isset($this->input['page_no']) && is_numeric($this->input['page_no']) ? (int)$this->input['page_no'] : 1;
            $limit = isset($this->input['limit']) && is_numeric($this->input['limit']) ? (int)$this->input['limit'] : 10;

            $sortBy = $this->input['sort_by'] ?? '';
            if ($sortBy) {
                $sort_type = $this->input['sort_type'] ?? 'ASC';
                $sortBy = $sortBy . ' ' . strtoupper($sort_type);
            }
            if($report_by == 'tax_per_wise') {
                $dbrs = $this->ReportModel->fetchGSTReportTaxPerWise($this->user_data->comp_id, $whstring, $page_no, $limit, $sortBy);
            } else if($report_by == 'state_wise') {
                $dbrs = $this->ReportModel->fetchGSTReportStateWise($this->user_data->comp_id, $whstring, $page_no, $limit, $sortBy);
            } else if($report_by == 'item_wise') {
                $dbrs = $this->ReportModel->fetchGSTReportItemWise($this->user_data->comp_id, $this->user_data->company_name, $whstring, $page_no, $limit, $sortBy);
            } else if($report_by == 'hsn_wise') {
                $dbrs = $this->ReportModel->fetchGSTReportHSNWise($this->user_data->comp_id, $whstring);
            } else if($report_by == 'hsn_summary_wise') {
                $dbrs = $this->ReportModel->fetchGSTReportHSNSummaryWise($this->user_data->comp_id, $whstring);
            } else if($report_by == 'reg_unreg_wise') {
                $dbrs = $this->ReportModel->fetchGSTReportRegisteredAndUnRegisteredWise($this->user_data->comp_id, $whstring);
            } else {
                $dbrs = $this->ReportModel->fetchGSTReport($this->user_data->comp_id, $whstring, $page_no, $limit, $sortBy, $report_by);
            } 
            if(empty($dbrs['status'])) {
                throw new \Exception($dbrs['error']);
            }
            $this->sendResponse([
                'code' => 200,
                'message' => 'Data fetched successfully',
                'data' => $dbrs['data'],
                'count' => !empty($dbrs['count'])?$dbrs['count']:0,
                'page' => !empty($dbrs['page'])?$dbrs['page']:$page_no,
                'page_limit' => !empty($dbrs['page_limit']) ? $dbrs['page_limit'] : $limit
            ]);
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => "Something went wrong while getting report", 'data' => $e->getMessage()));
        }
    }

    function getInventoryReport() {
        try {
            $page_no = isset($this->input['page_no']) && is_numeric($this->input['page_no']) ? (int)$this->input['page_no'] : 1;
            $limit = isset($this->input['limit']) && is_numeric($this->input['limit']) ? (int)$this->input['limit'] : 10;

            $sortBy = $this->input['sort_by'] ?? '';
            if ($sortBy) {
                $sort_type = $this->input['sort_type'] ?? 'ASC';
                $sortBy = $sortBy . ' ' . strtoupper($sort_type);
            }

            $branch_list = $this->FxModel->getBranchRightsOwned($this->user_data->comp_id, $this->user_data);                
            if(empty($branch_list['status'])) {
                throw new \Exception($branch_list['error']);
            }
            $branches = !empty($branch_list['data'])? explode(",", $branch_list['data']) : [];

            $wharr = [];
            $report_by = '';
            $subwhere = "";
            if(!empty($this->input['search'])) {
                foreach($this->input['search'] as $field=>$value) {
                    if($field == 'branch_id') {
                        if(!empty($value)) {
                            if($this->user_data->master_type != 1 && in_array($value, $branches)) {
                                $wharr['branch_id'] = $value;
                            }
                        } else if($this->user_data->master_type != 1 && !empty($branch_list['data'])) {
                            $wharr['branch_id_in'] = $branch_list['data'];
                        }
                    } else if($field == 'report_by') {
                        $report_by = strtolower($value);
                        if($report_by == 'branch_wise') {
                            $wharr['branch_id_not_null'] = NULL;
                            $sortBy = "s.branch_id";
                        } else {
                            $sortBy = "i.item_id";
                        }
                    } else if($field == 'item_stock') {
                        if($value == 'with_stock') {
                            $wharr['stock_plus'] = 0;
                        } else if($value == 'negative_stock') {
                            $wharr['stock_minus'] = 0;
                        } else if($value == 'nill_stock') {
                            $subwhere .= !empty($subwhere) ? " AND (s.stock = 0 or s.stock is NULL) " : " (s.stock = 0 or s.stock is NULL) ";
                        } else if($value == 'rol') {
                            $subwhere .= !empty($subwhere) ? " AND (s.stock < s.rol  AND s.rol>0) " : " (s.stock < s.rol  AND s.rol>0) ";
                        }
                    } else {
                        $wharr[$field] = $value;
                    }
                }    
            }
            $whstring = $this->FxModel->whereString(
                $wharr,
                array('*' => 'i.', 'branch_id' => 's.', 'stock'=>'s.'),
                array('branch_id_in'=>'IN', 'item_name' => 'LIKE', 'item_code' => 'LIKE', 'stock_plus'=>'GT', 'stock_minus'=>'LT', 'branch_id_not_null'=>'ISNOTNULL'), 
                array('branch_id_in'=>'branch_id', 'stock_plus'=>'stock', 'stock_minus'=>'stock', 'branch_id_not_null'=>'branch_id')
            );
            $whstring .= !empty($subwhere) ? " AND " .$subwhere : "";
            $dbrs = $this->ReportModel->fetchReportInventory($this->user_data->comp_id, $whstring, $page_no, $limit, $sortBy, $report_by);
            if(empty($dbrs['status'])) {
                throw new \Exception($dbrs['error']);
            } 
            $this->sendResponse([
                'code' => 200,
                'message' => 'Data fetched successfully',
                'data' => $dbrs['data'],
                'count' => !empty($dbrs['count'])?$dbrs['count']:0,
                'page' => !empty($dbrs['page'])?$dbrs['page']:$page_no,
                'page_limit' => !empty($dbrs['page_limit']) ? $dbrs['page_limit'] : $limit
            ]);
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => "Something went wrong while getting Inventory Report", 'data' => $e->getMessage()));
        }
    }

    private function getLeadConversionDashboard($comp_id, $filters) {
        try {
            $dbrs = $this->ReportModel->getLeadConversionDashboardData($comp_id, $filters);
            if(empty($dbrs['status'])) {
                throw new \Exception($dbrs['error']);
            } 
            if(empty($dbrs['data']) || count($dbrs['data']) < 4) {
                throw new \Exception("Incomplete data received from Lead Conversion Dashboard Data");
            }
            
            $pie_chart_data = array("label"=>[], "data"=>[]);
            $prev_pie_chart_data = array("label"=>[], "data"=>[]);
            if (isset($dbrs['data'][1])) {
                foreach ($dbrs['data'][1] as $key => $row) {
                    if (isset($row['lead_name']) && isset($row['Leads'])) {
                        $pie_chart_data['label'][] = $row['lead_name'];
                        $pie_chart_data['data'][] = (int)$row['Leads'];
                        $pie_chart_data['color'][] = $this->colors[$key % count($this->colors) ];
                    }
                }
            }
            if (isset($dbrs['data'][3])) {
                foreach ($dbrs['data'][3] as $key => $row) {
                    if (isset($row['lead_name']) && isset($row['Leads'])) {
                        $prev_pie_chart_data['label'][] = $row['lead_name'];
                        $prev_pie_chart_data['data'][] = (int)$row['Leads'];
                        $prev_pie_chart_data['color'][] = $this->colors[$key % count($this->colors) ];
                    }
                }
            }
            $lead_data = $dbrs['data'][0][0];
            if(isset($dbrs['data'][4])) {
                $lead_data['Today_Lead'] = (int) $dbrs['data'][4][0]['Today_Lead'];
                $lead_data['PreviousDay_Lead'] = (int) $dbrs['data'][4][0]['PreviousDay_Lead'];
                $today_leads = (int) $dbrs['data'][4][0]['Today_Lead'];
                $prev_day_leads = (int) $dbrs['data'][4][0]['PreviousDay_Lead'];
                $lead_change_per = 0;
                if($prev_day_leads > 0) {
                    $lead_change_per = round((($today_leads - $prev_day_leads) / $prev_day_leads) * 100, 2);
                }
                $lead_data['Lead_Change_Percentage'] = is_finite($lead_change_per) ? $lead_change_per : 0;
            }
            $area_chart_category_labels = [];
            if (isset($dbrs['data'][2])) {
                $labels = [];
                foreach ($dbrs['data'][2] as $row) {
                    if (isset($row['Month_wise'])) {
                        $labels[] = $row['Month_wise'];
                    }
                }
                $area_chart_category_labels = array_map(function($label) {
                    $date = \DateTime::createFromFormat('M-Y', $label);
                    return $date ? $date->format('M') : null;
                }, $labels);
            }
            $area_leads = [];
            $area_converted_leads = [];
            if (isset($dbrs['data'][2])) {
                foreach ($dbrs['data'][2] as $row) {
                    $area_leads[]   = isset($row['Leads']) ? (int)$row['Leads'] : 0;
                    $area_converted_leads[]   = isset($row['Converted_Leads']) ? (int)$row['Converted_Leads'] : 0;
                }
            }
            $lead_types = [];
            $lead_conv_data = [];
            $prev_lead_conv_data = [];
            if(!empty($dbrs['data'][1])) {
                foreach($dbrs['data'][1] as $row) {
                    $lead_types[$row['lead_name']] = $row['lead_name'];
                    $lead_conv_data[$row['lead_name']] = $row;
                }
            }
            if(!empty($dbrs['data'][3])) {
                foreach($dbrs['data'][3] as $row) {
                    $lead_types[$row['lead_name']] = $row['lead_name'];
                    $prev_lead_conv_data[$row['lead_name']] = $row;
                }
            }
            $lead_order_table = view('lead_conversion_table', ['lead_types'=>$lead_types, 'lead_data'=>$lead_conv_data]);
            $prev_day_lead_order_table = view('lead_conversion_table', ['lead_types'=>$lead_types, 'lead_data'=>$prev_lead_conv_data]);
            return ["status"=>true, "data"=>[
                'lead_data' => $lead_data,
                'lead_order_table' => $lead_order_table,
                'prev_lead_order_table' => $prev_day_lead_order_table,
                'pie_chart_data'=> $pie_chart_data,
                'prev_pie_chart_data'=> $prev_pie_chart_data,
                'area_chart_data'=> [
                    'leads' => $area_leads,
                    'converted_leads' => $area_converted_leads,
                    'area_chart_category_labels'=> $area_chart_category_labels   
                ]
            ]];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            return ["status"=>false, "error"=>"Something went wrong while getting Lead Conversion Dashboard Data"];
        }
    }  

    private function getSaleDashboard($comp_id, $filters) {
        try {
            $dbrs = $this->ReportModel->getSaleDashboardData($comp_id, $filters);
            if(empty($dbrs['status'])) {
                throw new \Exception($dbrs['error']);
            } 
            if(empty($dbrs['data']) || count($dbrs['data']) < 4) {
                throw new \Exception("Incomplete data received from Sale Dashboard Data");
            }
            $total_order = 0;
            
            $order_chart_data = array("label"=>[], "data"=>[]);
            $confirm_order_chart_data = array("label"=>[], "data"=>[]);
            $delivery_chart_data = array("label"=>[], "data"=>[]);
            $payment_chart_data = array("label"=>[], "data"=>[]);
            
            if(!empty($dbrs['data'][0])) {
                $i=0;
                foreach($dbrs['data'][0][0] as $key=>$val) {
                    $total_order += $val ? $val : 0;
                    $order_chart_data['label'][] = $key;
                    $order_chart_data['data'][] = $val ? (int) $val : 0;
                    $order_chart_data['color'][] = $this->colors[$i % count($this->colors) ];
                    $i++;
                }
            }

            if (!empty($dbrs['data'][1])) {
                $i=0;
                foreach ($dbrs['data'][1][0] as $key => $val) {
                    $delivery_chart_data['label'][] = $key;
                    $delivery_chart_data['data'][] = $val ? (int) $val : 0;
                    $delivery_chart_data['color'][] = $this->colors[$i % count($this->colors) ];
                    $i++;
                }
            }
            if (!empty($dbrs['data'][2])) {
                $i=0;
                foreach ($dbrs['data'][2][0] as $key => $val) {
                    if(in_array(strtolower($key), ['whatsapp_confirm_count'])) {
                        $confirm_order_chart_data['label'][] = $key;
                        $confirm_order_chart_data['data'][] = $val ? (int) $val : 0;
                        $confirm_order_chart_data['color'][] = $this->colors[$i % count($this->colors) ];
                        $i++;
                    }
                }
            }
            if (!empty($dbrs['data'][3])) {
                $i=0;
                foreach ($dbrs['data'][3][0] as $key => $val) {
                    if(in_array(strtolower($key), ['manual_confirm_count'])) {
                        $confirm_order_chart_data['label'][] = $key;
                        $confirm_order_chart_data['data'][] = $val ? (int) $val : 0;
                        $confirm_order_chart_data['color'][] = $this->colors[$i % count($this->colors) ];
                        $i++;
                    }
                }
            }
            if (!empty($dbrs['data'][4])) {
                $i=0;
                foreach ($dbrs['data'][4][0] as $key => $val) {
                    if(in_array(strtolower($key), ['partial_payment_amount','full_payment','cod'])) {
                        $payment_chart_data['label'][] = $key;
                        $payment_chart_data['data'][] = $val ? (int) $val : 0;
                        $payment_chart_data['color'][] = $this->colors[$i % count($this->colors) ];
                        $i++;
                    }
                }
            }
            return ["status"=>true, "data"=>[
                "total_order" => $total_order, 
                "average_order_value"=>isset($dbrs['data'][5]) ? (float) $dbrs['data'][5][0]['average_order_value'] : 0.00,
                "payment_chart_data" => $payment_chart_data,
                "confirm_order_chart_data" => $confirm_order_chart_data,
                "delivery_chart_data" => $delivery_chart_data,
                "order_chart_data" => $order_chart_data
            ]];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            return ["status"=>false, "error"=>"Something went wrong while getting Sale Report Dashboard Data"];
        }
    }

    private function getDeliveryDashboard($comp_id, $filters) {
        try {
            $dbrs = $this->ReportModel->getDeliveryDashboardData($comp_id, $filters);
            if(empty($dbrs['status'])) {
                throw new \Exception($dbrs['error']);
            } 
            if(empty($dbrs['data']) || count($dbrs['data']) < 3) {
                throw new \Exception("Incomplete data received from Delivery Dashboard Data");
            }
            
            $delivery_data = [];
            $courier_chart_data = [];
            $zone_chart_data = [];
            
            if(!empty($dbrs['data'][0])) {
                $i=0;
                foreach($dbrs['data'][0][0] as $key=>$val) {
                    $title = str_replace("_", " ", $key);
                    $delivery_data[] = ["title"=>$title, "count"=>(int) $val, "color_code"=>$this->colors[$i % count($this->colors)]];
                    $i++;
                }
            }
            if(!empty($dbrs['data'][1])) {
                $courier_chart_data = ["lables"=>[], "series"=>[
                    ["name"=>"Total Orders", "data"=>[]],
                    ["name"=>"Booked", "data"=>[]],
                    ["name"=>"In Transit", "data"=>[]],
                    ["name"=>"FAD", "data"=>[]],
                    ["name"=>"RAD", "data"=>[]],
                    ["name"=>"RTO", "data"=>[]],
                ]];
                foreach($dbrs['data'][1] as $i=>$row) {
                    $courier_chart_data['lables'][] = $row['Courier_Name'];
                    $courier_chart_data['series'][0]['data'][] = $row['Total_Orders'];
                    $courier_chart_data['series'][1]['data'][] = $row['Booked'];
                    $courier_chart_data['series'][2]['data'][] = $row['In_transit'];
                    $courier_chart_data['series'][3]['data'][] = $row['FAD'];
                    $courier_chart_data['series'][4]['data'][] = $row['RAD'];
                    $courier_chart_data['series'][5]['data'][] = $row['RTO'];
                }
            }
            if(!empty($dbrs['data'][2])) {
                $zone_chart_data = ["lables"=>[], "series"=>[
                    ["name"=>"Total Orders", "data"=>[]],
                    ["name"=>"Booked", "data"=>[]],
                    ["name"=>"In Transit", "data"=>[]],
                    ["name"=>"FAD", "data"=>[]],
                    ["name"=>"RAD", "data"=>[]],
                    ["name"=>"RTO", "data"=>[]],
                ]];
                foreach($dbrs['data'][2] as $i=>$row) {
                    $zone_chart_data['lables'][] = $row['Zone'];
                    $zone_chart_data['series'][0]['data'][] = $row['Total_Orders'];
                    $zone_chart_data['series'][1]['data'][] = $row['Booked'];
                    $zone_chart_data['series'][2]['data'][] = $row['In_transit'];
                    $zone_chart_data['series'][3]['data'][] = $row['FAD'];
                    $zone_chart_data['series'][4]['data'][] = $row['RAD'];
                    $zone_chart_data['series'][5]['data'][] = $row['RTO'];
                }
            }
            
            $table_courier_wise = view('shipment_status_table', ['type_title'=>'Courier', 'type_key'=>'Courier_Name', 'records'=>$dbrs['data'][1]]);
            $table_zone_wise = view('shipment_status_table', ['type_title'=>'Zone', 'type_key'=>'Zone', 'records'=>$dbrs['data'][2]]);
            
            return ["status"=>true, "data"=>[
                "delivery_data" => $delivery_data,
                "courier_chart_data" => $courier_chart_data,
                "zone_chart_data" => $zone_chart_data,
                "table_courier_wise" => $table_courier_wise,
                "table_zone_wise" => $table_zone_wise
            ]];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            return ["status"=>false, "error"=>"Something went wrong while getting Sale Report Dashboard Data"];
        }
    }

    function getDashboarData() {
        try {
            if(empty($this->input['dashboard_type'])) {
                throw new \Exception("Dashboard Type is required");
            }
            if(empty($this->input['search'])) {
                throw new \Exception("Search parameters are required");
            }
            if(empty($this->input['search']['lead_date'])) {
                throw new \Exception("Lead date range is required");
            }
            $filters = [
                'user_id'=> $this->input['search']['user_id'] ? implode(",", $this->input['search']['user_id']) : '',
                'tl_id'=> $this->input['search']['tl_id'] ? implode(",", $this->input['search']['tl_id']) : '',
                'manager_id'=> $this->input['search']['manager_id'] ? implode(",", $this->input['search']['manager_id']) : '',
                'lead_type' => $this->input['search']['lead_type'] ? implode(",", $this->input['search']['lead_type']) : '',
                'from_date'=> NULL,
                'to_date'=> NULL,
                'prev_from_date'=> NULL,
                'prev_to_date'=> NULL
            ];
            if(!empty($this->input['search']['lead_date'])) {
                $filters['from_date'] = !empty($this->input['search']['lead_date'][0]) ? date('Y-m-d H:i:s', strtotime($this->input['search']['lead_date'][0])) : NULL;
                $filters['to_date'] = !empty($this->input['search']['lead_date'][1]) ? date('Y-m-d H:i:s', strtotime($this->input['search']['lead_date'][1])) : NULL;
            }
            if(!empty($this->input['search']['previous_lead_date'])) {
                $filters['prev_from_date'] = !empty($this->input['search']['previous_lead_date'][0]) ? date('Y-m-d H:i:s', strtotime($this->input['search']['previous_lead_date'][0])) : NULL;
                $filters['prev_to_date'] = !empty($this->input['search']['previous_lead_date'][1]) ? date('Y-m-d H:i:s', strtotime($this->input['search']['previous_lead_date'][1])) : NULL;
            }
            if(strtolower($this->input['dashboard_type']) == 'lead_conversion') {
                $dashrs = $this->getLeadConversionDashboard($this->user_data->comp_id, $filters);
                if(empty($dashrs['status'])) {
                    throw new \Exception($dashrs['error']);
                }
                $this->sendResponse(['code' => 200, 'message' => 'Data fetched successfully', 'data' => $dashrs['data']]);
            } else if(strtolower($this->input['dashboard_type']) == 'sales_dashboard') {
                $dashrs = $this->getSaleDashboard($this->user_data->comp_id, $filters);
                if(empty($dashrs['status'])) {
                    throw new \Exception($dashrs['error']);
                }
                $this->sendResponse(['code' => 200, 'message' => 'Data fetched successfully', 'data' => $dashrs['data']]);
            } else if (strtolower($this->input['dashboard_type']) == 'delivery_dashboard') {
                $dashrs = $this->getDeliveryDashboard($this->user_data->comp_id, $filters);
                if(empty($dashrs['status'])) {
                    throw new \Exception($dashrs['error']);
                }
                $this->sendResponse(['code' => 200, 'message' => 'Data fetched successfully', 'data' => $dashrs['data']]);
            } else {
                throw new \Exception("Invalid Dashboard Type");
            }
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => "Something went wrong while getting Sale Report Dashboard Data", 'data' => $e->getMessage()));
        }
    }
}