<?php
defined('BASEPATH') or exit('No direct script access allowed');
include APPPATH.'/third_party/faker/autoload.php';
class Api extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        defined('DASHBOARDS_MODULE') or exit(blank_page());
        $this->load->model('dashboard_model');
        $this->load->model('sql_model');
        $this->load->model('opportunities_model');
        $this->load->library('dashboard');
        $this->load->model('dashboard_period_filter_v2');
    }

    public function translations($language = 'english'){
      header('Content-Type: text/json');
      echo json_encode([
        'en'=>[
          'message'=> [
              'current_opportunities'=> _l('message.current_opportunities'),
              'one_time_fee'=> _l('message.one_time_fee'),
              'monthly_recurryng_fee'=> _l('message.monthly_recurryng_fee'),
              'average_purchase_rate'=> _l('message.average_purchase_rate'),
              'chart_reasons_lost_opportunities'=> _l('message.chart_reasons_lost_opportunities'),
              'win_rate'=> _l('message.win_rate'),
              'lostOpportunities'=> _l('message.lostOpportunities'),
              'lost_purchase_otf'=>_l('message.lost_purchase_otf'),
              'lost_purchase_mrr'=> _l('message.lost_purchase_mrr'),
              'details_opportunities'=> _l('message.details_opportunities'),
              'current_purchase'=> _l('message.current_purchase'),
              'stage_name'=> _l('message.stage_name'),
              'sales_person'=> _l('message.sales_person'),
              'last_month'=> _l('message.last_month'),
              'no_last_month'=> _l('message.no_last_month'),
              'period'=> _l('message.period'),
              'table'=> [
                  'id'=> _l("message.table.id"),
                  'first_contact'=> _l("message.table.first_contact"),
                  'company'=> _l("message.table.company"),
                  'opp_stage'=> _l("message.table.opp_stage"),
                  'last_status'=> _l("message.table.last_status"),
              ]
          ],
          'sales_conversion'=> [
              'chart_title_lead_convertion_ratio'=> _l('chart_title_lead_convertion_ratio'),
              'chart_subtitle_lead_convertion_ratio'=> _l('chart_subtitle_lead_convertion_ratio'),
              'chart_title_leads'=> _l('chart_title_leads'),
              'chart_title_opportunitites'=> _l('chart_title_opportunitites'),
              'default_converted_leads'=> _l('default_converted_leads'),
              'leads_to_opportunity'=> _l('leads_to_opportunity'),
              'opportunity_to_win'=> _l('opportunity_to_win'),
          ],
          'okr_dashboard'=> [
              'okr_progressing_well'=> _l('okr_progressing_well'),
              'progress_this_week'=> _l('progress_this_week'),
              'okr_developing'=> _l('okr_developing'),
              'okr_risk'=> _l('okr_risk'),
              'okrs_company'=> _l('okrs_company'),
              'objective'=> _l('objective'),
              'progress'=> _l('progress'),
              'key_results'=> _l('key_results'),
              'confidence_level'=> _l('confidence_level'),
              'my_okrs'=> _l('my_okrs'),
              'check_in_status'=> _l('check_in_status'),
          ],
          'ceo_strategic'=> [
            'new_revenue'=> _l('title_new_revenue'),
            'all_channels'=> _l('all_channels'),
          ],

          'charts'=> [
            'new_revenue'=> _l('title_new_revenue'),
            'all_channels'=> _l('all_channels'),
            'chart__revenue_accomplished'=> _l('chart__revenue_accomplished'),
            'chart__revenue_to_target'=> _l('chart__revenue_to_target'),
            'chart__income_and_expenses_accomplished'=> _l('chart__income_and_expenses_accomplished'),
            'chart__income_and_expenses_to_target'=> _l('chart__income_and_expenses_to_target'),
            'chart__gross_profit_accomplished'=> _l('chart__gross_profit_accomplished'),
            'chart__gross_profit_to_target'=> _l('chart__gross_profit_to_target'),
            'chart__ebit_accomplished'=> _l('chart__ebit_accomplished'),
            'chart__ebit_to_target'=> _l('chart__ebit_to_target'),
            'toggle_direction'=> _l('toggle_direction'),
            'toggle_gradient_direction'=> _l('toggle_gradient_direction'),
            'chart__tickets_by_h__num_tickets'=> _l('chart__tickets_by_h__num_tickets'),
            'chart__tickets_by_h__perc_tickets'=> _l('chart__tickets_by_h__perc_tickets'),
            'chart__hourly_tickets_by_month__tickets'=> _l('chart__hourly_tickets_by_month__tickets'),
            'chart__hourly_tickets_by_month__of_all'=> _l('chart__hourly_tickets_by_month__of_all'),
            'chart__hourly_tickets_by_month__y_tickets_filtered'=> _l('chart__hourly_tickets_by_month__y_tickets_filtered'),
            'chart__hourly_tickets_by_month__y_all_tickets'=> _l('chart__hourly_tickets_by_month__y_all_tickets'),
            'chart__daily_tickets_by_month__per_day'=> _l('chart__daily_tickets_by_month__per_day'),
            'chart__daily_tickets_by_month__all_time_per_day'=> _l('chart__daily_tickets_by_month__all_time_per_day'),
            'chart__daily_tickets_by_month___title_per_day'=> _l('chart__daily_tickets_by_month___title_per_day'),
            'chart__response_time_trend__minutes'=> _l('chart__response_time_trend__minutes'),
            'chart__response_time_trend__alltime_trend'=> _l('chart__response_time_trend__alltime_trend'),
            'chart__response_time_trend__ytitle_column'=> _l('chart__response_time_trend__ytitle_column'),
            'chart__response_time_trend__ytitle_spline'=> _l('chart__response_time_trend__ytitle_spline'),
            'chart__income__sales'=> _l('chart__income__sales'),
            'chart__expenses__title'=> _l('chart__expenses__title'),
            'chart__net_profit__title'=> _l('chart__net_profit__title'),

          ],
          'general'=> [
            'mo_Jan'=> _l('mo_Jan'),
            'mo_Feb'=> _l('mo_Feb'),
            'mo_Mar'=> _l('mo_Mar'),
            'mo_Apr'=> _l('mo_Apr'),
            'mo_May'=> _l('mo_May'),
            'mo_Jun'=> _l('mo_Jun'),
            'mo_Jul'=> _l('mo_Jul'),
            'mo_Aug'=> _l('mo_Aug'),
            'mo_Sep'=> _l('mo_Sep'),
            'mo_Oct'=> _l('mo_Oct'),
            'mo_Nov'=> _l('mo_Nov'),
            'mo_Dec'=> _l('mo_Dec'),
            "versus_previous_period"=>_l('versus_previous_period')
          ],
        ]
      ]);
    }

    public function get_statuses() {
        $data = $this->opportunities_model->get_status();
        echo json_encode($data); exit;
    }

    public function get_sales_conversion()
    {
      $payload = file_get_contents('php://input'); //$this->input->post('params');
      $payload = json_decode($payload,true);

      if(get_option('demo_mode') == '1'){
        $faker = Faker\Factory::create();
        $faker->addProvider(new  Faker\Provider\LeadsProvider($faker));

        $opportunities = $faker->leads(100,1000);
        $objOpportunities = $faker;

        $leads = $faker->leads(100,1000);
        $objLeads = $faker;

        $percents_opp = $faker->random_numbers_sum(12,$opportunities);
        $percents_leads = $faker->random_numbers_sum(12,$leads);


        $days_conversions =  $faker->random_numbers_sum(30,$faker->converted_clients());
        $converted_leads_arr = [];
        foreach($days_conversions as $k=>$v){
          $converted_leads_arr[] = [
            "name"=> "Day: ".($k+1),
              "color"=> "#1caf9a",
              "data"=> [
                $v
              ]
          ];
        }
        $converted_leads_json = json_encode($converted_leads_arr);

      $return = '{
        "results": {
          "global": {
            "new_customers": '.$faker->converted_clients().',
            "total_valid_entries": '.$leads.',
            "total_leads": '.$leads.',
            "total_opportunitites": '.$opportunities.',
            "total_leads_to_opportunitites": '.$faker->numberBetween(0,$leads).',
            "total_negociation": '.$leads.',
            "total_proposals": '.$leads.',
            "total_wins": '.$leads.',
            "total_status_1": '.$percents_opp[0].',
            "total_status_2": '.$percents_opp[1].',
            "total_status_3": '.$percents_opp[2].',
            "total_status_4": '.$percents_opp[3].',
            "total_status_5": '.$percents_opp[4].',
            "total_status_6": '.$percents_opp[5].',
            "total_status_7": '.$percents_opp[6].',
            "total_status_8": '.$percents_opp[7].',
            "total_status_9": '.$percents_opp[8].',
            "total_status_10": '.$percents_opp[9].',
            "total_lost": '.$percents_opp[10].',
            "total_junk": '.$percents_opp[11].',
            "from_date": "2022-09-15",
            "to_date": "2022-10-15",
            "text": {
              "title_chart_converted_leads": "Lead-uri convertite in ultimele 30 zile"
            }
          },
          "converted_leads": '.$converted_leads_json.',
          "perc_leads": '.$objLeads->generate_percent_1_of_2().',
          "perc_opp": '.$objLeads->generate_percent_2_of_2().',
          "leads_to_opportunity__title_text": "'.$objLeads->generate_percent_1_of_2().'%",
          "leads_to_opportunity": [
            {
              "name": "Opportunities",
              "color": "'.$faker->rgbaCssColor().'",
              "y": '.$opportunities.'
            },
            {
              "name": "Leads",
              "color": "'.$faker->rgbaCssColor().'",
              "y": '.$leads.'
            }
          ],
          "perc_wins_in_opp": '.$objOpportunities->generate_percent_1_of_2().',
          "perc_not_wins_in_opp": '.$objOpportunities->generate_percent_1_of_2().',
          "opportunity_to_win__title_text": "'.$objOpportunities->generate_percent_1_of_2().'%",
          "opportunity_to_win": [
            {
              "name": "Wins",
              "color": "'.$faker->rgbaCssColor().'",
              "y": '.$leads.'
            },
            {
              "name": "Opportunities",
              "color": "'.$faker->rgbaCssColor().'",
              "y": '.$opportunities.'
            }
          ],
          "sales_agents": [
      
          ],
          "valid_conversion_ratio": false,
          "leads_for_a_win": 0,
          "base_ration_leads_for_client": "1"
        },
        "code": "success"
      }';
      echo ($return); exit;
        
     }

      
      $data['results']['global'] = $this->dashboard_model->count_conversions($payload['params']);

      $this->dashboard_period_filter_v2->set_params($payload['params']);
      $global = $this->dashboard_period_filter_v2
        ->from('tblleads')->set_period_on($payload['params'],'dateadded')
        ->select('last_opportunity_status_change')
        ->select('
        (SELECT count(*) FROM '.db_prefix().'leads as t
          WHERE  is_opportunity = 1 AND lost = 0 AND junk = 0 AND (status_opportunity = 9)
          '.  $this->dashboard_period_filter_v2->return_date_filtering_on('last_opportunity_status_change','and').'
        ) as won_opp
        ')

        ->get_by_monthday();

        $won_opp = array_column($global,'won_opp');
        $won_opp = $this->dashboard->cast_int($won_opp);
        $categories = array_column($global,'display_format');
        foreach($won_opp as $k=>$v){
          $series_data[$k] = [
            'name'=>$categories[$k],
            //'y'=>$v,

            'color'=>'#1caf9a','data'=>[$v]
          ];
        }


        //pre($global);
      /*[
        'new_customers'=>1,
        'total_leads'=>'3',
        'total_opportunitites'=>'2',
        'total_negociation'=>'3',
        'total_proposals'=>'3',
        'total_wins'=>'3',
      ];*/

        $data['results']['converted_leads'] = $series_data;
        //$data['results']['converted_leads'] = $this->prepare_converted_leads($payload['params']);

        /*[
          ['color'=>'#1caf9a','data'=>[4]],
          ['color'=>'#1caf9a','data'=>[6]],
          ['color'=>'#1caf9a','data'=>[2]],
          ['color'=>'#1caf9a','data'=>[3]],
          ['color'=>'#1caf9a','data'=>[4]],
          ['color'=>'#1caf9a','data'=>[5]],
          ['color'=>'#1caf9a','data'=>[6]],
          ['color'=>'#1caf9a','data'=>[6]],
          ['color'=>'#1caf9a','data'=>[8]],
          ['color'=>'#1caf9a','data'=>[9]],
          ['color'=>'#1caf9a','data'=>[4]],
          ['color'=>'#1caf9a','data'=>[3]],
          ['color'=>'#1caf9a','data'=>[1]],
          ['color'=>'#1caf9a','data'=>[6]],

        ];*/

        $leads = $data['results']['global']['total_leads'];
        $opp = $data['results']['global']['total_opportunitites'];
        $total = $leads+$opp;
        $data['results']['perc_leads'] = $this->dashboard->percent_in($leads,$total);
        $data['results']['perc_opp'] = $this->dashboard->percent_in($opp,$total);
        $data['results']['leads_to_opportunity__title_text'] = (string)$data['results']['perc_opp'].'%';


        $data['results']['leads_to_opportunity'] = [
          ['name'=>'Opportunities','color'=>'rgba(26, 188, 156,1.0)','y'=>$data['results']['perc_opp']],
          ['name'=>'Leads','color'=>'rgba(26, 188, 156,0.5)','y'=>$data['results']['perc_leads']],
        ];


        $wins = $data['results']['global']['total_wins'];
        $opp = $data['results']['global']['total_opportunitites'];
        $other = $this->dashboard->substract($opp,$wins);

        $data['results']['perc_wins_in_opp'] = $this->dashboard->percent_in($wins,$opp);
        $data['results']['perc_not_wins_in_opp'] = $this->dashboard->percent_in($other,$opp);
        $data['results']['opportunity_to_win__title_text'] = (string)$data['results']['perc_wins_in_opp'].'%';



        $data['results']['opportunity_to_win'] = [
          ['name'=>'Wins','color'=>'rgba(26, 188, 156,1.0)','y'=>$data['results']['perc_wins_in_opp']],
          ['name'=>'Opportunities','color'=>'rgba(26, 188, 156,0.5)','y'=>$data['results']['perc_not_wins_in_opp']],
        ];
        //trnds: good, bad, ''



        $data['results']['sales_agents'] = $this->prepare_sales_agents($payload['params']);

        /*[
          ['name'=>'Bogdan','function'=>'Sales Manager','conversion_rate'=>15,'trend'=>'good'],
        ];*/

        $data['results']['global']['text']['title_chart_converted_leads'] = _l('default_converted_leads');
        if(isset($payload['params']['period_filter'])){
          if($payload['params']['period_filter'] == 't'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_today');
          }else if($payload['params']['period_filter'] == 'y'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_yesterday');
          }else if($payload['params']['period_filter'] == 'w'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_week');
          }else if($payload['params']['period_filter'] == 'lw'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_last_week');
          }else if($payload['params']['period_filter'] == 'm'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_month');
          }else if($payload['params']['period_filter'] == 'lm'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_last_month');
          }else if($payload['params']['period_filter'] == 'yr'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_year');
          }else if($payload['params']['period_filter'] == 'lyr'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_last_year');
          }else if($payload['params']['period_filter'] == 'p'){
            $data['results']['global']['text']['title_chart_converted_leads'] = sprintf(_l('title_chart_converted_leads_interval'), $payload['params']['date_from'],$payload['params']['date_to']);
          }else if($payload['params']['period_filter'] == '30d'){
            $data['results']['global']['text']['title_chart_converted_leads'] = _l('title_chart_converted_leads_30d');
          }

        }

        $data['results']['valid_conversion_ratio'] = true;
        $data['results']['leads_for_a_win'] = $this->dashboard->division($opp,$wins,1);
        $data['results']['base_ration_leads_for_client'] = '1';
        if($data['results']['leads_for_a_win'] == 0){ $data['results']['valid_conversion_ratio'] = false; }

        $data['code'] = 'success';

        echo json_encode($data); exit;
    }

    public function prepare_sales_agents($params){
      $results = $this->dashboard_model->sales_agents_with_conversions($params);
      if(!empty($results)){
        foreach($results as $k=>$result){
          if((int)$result['owned_converted_leads'] == 0){
            $results[$k]['conversion_rate'] = 0;
          }else{
            if($result['owned_leads'] != 0){
              $results[$k]['conversion_rate'] = round(($result['owned_converted_leads']/$result['owned_leads'])*100);
            }else{
              $results[$k]['conversion_rate'] = 0;
            }
          }

          $results[$k]['trend'] = '';
        }
      }
      return $results;
    }
    public function prepare_converted_leads($params){
      $results = $this->dashboard_model->converted_leads($params);
      $return = [];
      //  ['color'=>'#1caf9a','data'=>[5]],
      if(!empty($results)){
        foreach($results as $k=>$result){
          $return[] =  ['color'=>'#1caf9a','data'=>[(int)$result['total_counted']],'name'=>$result['the_date']];

        }
      }
      return $return;
    }


}
