<?php
defined('BASEPATH') or exit('No direct script access allowed');
include APPPATH.'/third_party/faker/autoload.php';

class Cfo_strategic extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        defined('DASHBOARDS_MODULE') or exit(blank_page());
        $this->load->model('dashboard_model');
        $this->load->model('currencies_model');
        $this->load->library('dashboard');
        $this->load->model('dashboard_period_filter_v2');
        $this->base_currency = $this->currencies_model->get_base_currency();
    }

    public function index()
    {
        close_setup_menu();
        $data['title']  = _l(DASHBOARDS_MODULE.'_'.$this->router->fetch_class());
        if (!has_permission(DASHBOARDS_MODULE, '', $this->router->fetch_class())  && !is_admin()) {
            access_denied(DASHBOARDS_MODULE);
        }
        $this->load->model('filtering_model');
        $this->load->view($this->router->fetch_class(), $data);
    }
    public function piecharts(){
      if(get_option('demo_mode') == '1'){
        $faker = Faker\Factory::create();
        $faker->addProvider(new  Faker\Provider\LeadsProvider($faker));
        $revenue = $faker->completed_amount(10000,100000);
        $rObj = $faker;

        $gross_profit = $faker->completed_amount(1000,10000);
        $grossObj = $faker;

        $addition = $faker->completed_amount(1000,10000);
        $additionObj = $faker;

        $return = [
            'status'=>true,
            'revenue'=>$revenue,
            'revenue_formatted'=>$revenue.' '.$this->base_currency->symbol,
            'revenue_target'=>$rObj->target_objective(),
            'revenue_target_formatted'=>$rObj->target_objective().' '.$this->base_currency->symbol,
            'percent_to_target'=>$rObj->uncompleted_percent(),
            'percent_revenue'=>$rObj->completed_percent(),
  
            'percent_income'=>$faker->generate_percent_1_of_2(),
            'percent_expenses'=>$faker->generate_percent_2_of_2(),
            'income_expenses_ratio_target'=>'1:2',
            'income_expenses_ratio'=>'1:2',
  
            'gross_profit_target'=>$grossObj->target_objective(),
            'gross_profit'=>$gross_profit,
            //'percent_gross_profit'=>100,
            'percent_gross_profit'=>$grossObj->completed_percent(),
            'percent_gross_profit_formatted'=>$grossObj->completed_percent().' '.$this->base_currency->symbol,
            'percent_gross_profit_totarget'=>$grossObj->uncompleted_percent(),
            'percent_gross_profit_totarget_formatted'=>$grossObj->uncompleted_amount().' '.$this->base_currency->symbol,
  
            'addition_target'=>$additionObj->uncompleted_amount(),
            'addition_total'=>$additionObj->target_objective(),
            'addition_accomplished'=>$additionObj->completed_percent().'%',
            'addition_to_target'=>$additionObj->uncompleted_percent().'%',
            'percent_addition_accomplished'=>$additionObj->completed_percent(),
            'percent_addition_to_target'=>$additionObj->uncompleted_percent(),
            
  
            'has_revenue_goal'=>$rObj->target_objective(),
            'has_inc_vs_exp_ratio_goal'=>2,
            'has_gross_margin_goal'=>$grossObj->target_objective(),
            'has_addition_goal'=>$additionObj->target_objective(),
  
        ];
      echo json_encode($return); exit;



      }
      $this->load->model('goals/goals_model');
      $payload = file_get_contents('php://input'); //$this->input->post('params');
      $payload = json_decode($payload,true);

      $this->dashboard_period_filter_v2->reset();
      $revenue = $this->dashboard_period_filter_v2
        ->from('tblinvoices')->set_period_on($payload['params'],'datecreated')
        ->select('sum(tblinvoices.total) as total_value')
        ->where('status !=',0)->where('status !=',null)
        ->number('total_value');

      $target = $revenue;

      $has_revenue_goal = false;
      $has_inc_vs_exp_ratio_goal = false;
      $has_gross_margin_goal = false;
      $has_addition_goal = false;

      $goal = $this->goals_model->get_by_type(1,$this->dashboard_period_filter_v2->from_date,$this->dashboard_period_filter_v2->to_date);
      if($goal){
        $target = $goal->achievement;
        $has_revenue_goal = true;
      }





      $remaining_to_target = $target-$revenue;
      $sum = $target+$revenue;
      $percent_to_target = $this->dashboard->percent_in($remaining_to_target,$sum);
      $percent_revenue = $this->dashboard->percent_in($revenue,$sum);

      //----

      $expenses = $this->dashboard_period_filter_v2
        ->from('tblexpenses')->set_period_on($payload['params'],'dateadded')
        ->select('sum(tblexpenses.amount) as total_value')
        ->number('total_value');

        $sum = $revenue+$expenses;
        $pie_revenue = $this->dashboard->percent_in($revenue,$sum);
        $pie_expenses = $this->dashboard->percent_in($expenses,$sum);

        $expenses_in_revenue = $this->dashboard->percent_in($expenses,$revenue);
        if($expenses_in_revenue != 0){
            $ratio = round((1/$expenses_in_revenue)*100);
        }else{
          $ratio = 0;
        }

        $ratio_target = $ratio;
        $goal = $this->goals_model->get_by_type(20,$this->dashboard_period_filter_v2->from_date,$this->dashboard_period_filter_v2->to_date);
        if($goal){
          $ratio_target = $goal->achievement;
          $has_inc_vs_exp_ratio_goal = true;
        }

        //----
        $gross_profit_target = 0;
        $goal = $this->goals_model->get_by_type(21,$this->dashboard_period_filter_v2->from_date,$this->dashboard_period_filter_v2->to_date);
        if($goal){
          $gross_profit_target = $goal->achievement;
          $has_gross_margin_goal = true;
        }

        $this->dashboard_period_filter_v2->reset();
        $gross_margin = $this->dashboard_period_filter_v2
          ->from('tblinvoices')->set_period_on($payload['params'],'date')

          ->join('tblitemable','tblinvoices.id = tblitemable.rel_id and rel_type = "invoice"')
          ->join('tblcurrencies','tblcurrencies.id = tblitemable.currency')
          ->join('tblitems','tblitems.id = tblitemable.item_id')
          ->join('tblcurrencies as item_curr','item_curr.id = tblitems.item_currency')
          ->group_by('tblinvoices.id')
          ->where('tblitems.purchase_price !=',null)
          ->select('AVG((tblitemable.rate + tblitems.purchase_price)/tblitemable.rate) as total_value')
          ->number('total_value');


        //------------

        $this->dashboard_period_filter_v2->reset();
        $addition = $this->dashboard_period_filter_v2
          ->from('tblinvoices')->set_period_on($payload['params'],'date')

          ->join('tblitemable','tblinvoices.id = tblitemable.rel_id and rel_type = "invoice"')
          ->join('tblcurrencies','tblcurrencies.id = tblitemable.currency')
          ->join('tblitems','tblitems.id = tblitemable.item_id')
          ->join('tblcurrencies as item_curr','item_curr.id = tblitems.item_currency')
          ->group_by('tblinvoices.id')
          ->where('tblitems.purchase_price !=',null)
          ->select('AVG((tblitemable.rate + tblitems.purchase_price)/tblitems.purchase_price) as total_value')
          ->number('total_value');
        $addition_target = 0;
        $goal = $this->goals_model->get_by_type(22,$this->dashboard_period_filter_v2->from_date,$this->dashboard_period_filter_v2->to_date);
        if($goal){
          $addition_target = $goal->achievement;
          $has_addition_goal = true;
        }


      $return = [
          'status'=>true,
          'revenue'=>$revenue,
          'revenue_formatted'=>$revenue.' lei',
          'revenue_target'=>$target,
          'revenue_target_formatted'=>$target.' lei',
          'percent_to_target'=>$percent_to_target,
          'percent_revenue'=>$percent_revenue,

          'percent_income'=>$pie_revenue,
          'percent_expenses'=>$pie_expenses,
          'income_expenses_ratio_target'=>'1:'.$ratio_target,
          'income_expenses_ratio'=>''.$ratio.':1',

          'gross_profit_target'=>$gross_profit_target,
          'gross_profit'=>$gross_margin,
          //'percent_gross_profit'=>100,
          'percent_gross_profit'=>(string)$gross_margin,
          'percent_gross_profit_formatted'=>(string)$gross_margin.''.'%',
          'percent_gross_profit_totarget'=>(string)$gross_profit_target.'',
          'percent_gross_profit_totarget_formatted'=>(string)$gross_profit_target.'%',

          'addition_target'=>$addition_target,
          'addition_total'=>$addition,
          'addition_accomplished'=>(string)$addition.'%',
          'addition_to_target'=>(string)$addition_target.'%',
          'percent_addition_accomplished'=>(int)$addition,
          'percent_addition_to_target'=>(int)$addition_target,
          

          'has_revenue_goal'=>$has_revenue_goal,
          'has_inc_vs_exp_ratio_goal'=>$has_inc_vs_exp_ratio_goal,
          'has_gross_margin_goal'=>$has_gross_margin_goal,
          'has_addition_goal'=>$has_addition_goal,

      ];
    echo json_encode($return); exit;

  }

}
