<?php defined('BASEPATH') or exit('No direct script access allowed');

class Development extends AdminController
{

  public function __construct()
  {
    parent::__construct();
    $this->load->helper(['form', 'url']);
    $this->load->library('form_validation');
    $this->load->model('development_model');

  }

  public function translate_strings()
  {
    if (!has_permission('development', '', 'view')) {
        access_denied('development');
    }
    $data['title'] = _l('development');

    $this->load->view('translate_strings/manage', $data);
  }
  public function translation_strings_datatable(){
    if (!has_permission('development', '', 'view')) {
      access_denied('development');
    }

    $this->load->model('development_model');

    $aColumns = [
      'id',
      'item',
      'romanian',
      'english',
      //'description',
      //'file',
      //'context',
      'module',
      'category',
     // 'namespace',
      //'found_in',
      
      //'(SELECT text FROM tbltranslation_text WHERE id_string = tbltranslation_strings.id AND id_language = 1 LIMIT 1) as englisht',
      //'(SELECT text FROM tbltranslation_text WHERE id_string = tbltranslation_strings.id AND id_language = 2 LIMIT 1) as romaniant',
      //'romanian.text as romaniant',
     // 'english.text as englisht',
    ];

    $sIndexColumn = 'id';
    $sTable       = db_prefix() . 'translation_strings';

    $where  = [];
    $filter = [];





    $result  = data_tables_init($aColumns, $sIndexColumn, $sTable, [], $where, ['id']);

    $output  = $result['output'];
    $rResult = $result['rResult'];

    foreach ($rResult as $aRow) {
      $row = [];
      $row[]  = $aRow['id'];
      $row[]  = $aRow['item'];
      $row[]  = '<span class="contentedt not-init" field="romanian" pk="'.$aRow['id'].'">'.$aRow['romanian'].'</span>';
      $row[]  = '<span class="contentedt not-init" field="english" pk="'.$aRow['id'].'">'.$aRow['english'].'</span>';
      //$row[]  = $aRow['description'];
      //$row[]  = $aRow['file'];
      //$row[]  = $aRow['context'];
      $row[]  = '<span class="contentedt not-init" field="module" pk="'.$aRow['id'].'">'.$aRow['module'].'</span>';
      $row[]  = '<span class="contentedt not-init" field="category" pk="'.$aRow['id'].'">'.$aRow['category'].'</span>';
      //$row[]  = '<span class="contentedt not-init" field="namespace" pk="'.$aRow['id'].'">'.$aRow['namespace'].'</span>';
      //$row[]  = $aRow['found_in'];
      
      //$row[]  = $aRow['romaniant'];
      //$row[]  = $aRow['englisht'];
    

      $action
      = '<a type="button" class="btn btn-sm btn-outline-secondary" href="' . admin_url('development/edit_translations/' . $aRow['id']) . '"><i class="fal fa-edit"></i></a>'
              . '<a type="button" class="btn btn-sm btn-danger" href="' . admin_url('development/delete_translation/' . $aRow['id']) . '"><i class="fal fa-trash"></i></a>';

      $row[]              = $action;
      $output['aaData'][] = $row;
    }

    echo json_encode($output);
    die();
  }



  public function edit_translations($id = null)
  {
    
    if (!has_permission('development', '', 'view')) {
      access_denied('development');
    }

    if ($this->input->post() && !$this->input->is_ajax_request()) {
      $data = $this->input->post();
      //$this->form_validation->set_rules('string[]', _l('development'), 'required');
      $this->form_validation->set_rules('english', _l('english'), 'required');
      if ($this->form_validation->run() === true) {
        if (!$id) {
          $id = $this->development_model->add_item($data);

            set_alert('success', _l('updated_successfully', _l('development')));

        } else {
            $this->development_model->update_item($data, $id);
            set_alert('success', _l('updated_successfully', _l('development')));
        }
        redirect(admin_url('development/edit_translations/' . $id));
      }
    }elseif ($this->input->post() && $this->input->is_ajax_request()){
      $data = $this->input->post();
      $response = [];
        if (!$id) {
            $response['code'] = 'error';
            echo json_encode($response);exit;

        } else {
            $response['code'] = 'success';
            $this->development_model->update_item($data, $id);
            echo json_encode($response);exit;
        }     

    }

    if ($id) {
      /*$translations = $this->development_model->get_translations($id);
      if (!$translations) {
        show_404();
      }*/
    }
    //$data['translations'] = $translations;
    $data['string'] =  $this->development_model->get_string($id);
    $data['modules'] = [
      ['name'=>'api'],
      ['name'=>'appointly'],
      ['name'=>'assets'],
      ['name'=>'billing'],
      ['name'=>'commision'],
      ['name'=>'crmcon_email_builder'],
      ['name'=>'custom_email_and_sms_notifications'],
      ['name'=>'dashboards'],
      ['name'=>'diagramy'],
      ['name'=>'essential_package'],
      ['name'=>'startup_package'],
      ['name'=>'pro_package'],
      ['name'=>'facebook_leads_integration'],
      ['name'=>'goals'],
      ['name'=>'hr'],
      ['name'=>'mailbox'],
      ['name'=>'marketing_campaigns'],
      ['name'=>'menu_builder'],
      ['name'=>'menu_setup'],
      ['name'=>'minutes'],
      ['name'=>'okr'],
      ['name'=>'omni_sales'],
      ['name'=>'packages_manager'],
      ['name'=>'prchat'],
      ['name'=>'project_roadmap'],
      ['name'=>'purchase'],
      ['name'=>'recruitment'],
      ['name'=>'remarketing'],
      ['name'=>'resource_workload'],
      ['name'=>'scoring'],
      ['name'=>'services'],
      ['name'=>'si_export_customer'],
      ['name'=>'surveys'],
      ['name'=>'team_password'],
      ['name'=>'theme_style'],
      ['name'=>'warehouse'],
      ['name'=>'whatsapp_chat'],
    ];
    if (!isset($data['id'])) $data['id'] = null;

    if (set_value('id', $data['id'] ?? null)){
        $data['title'] = _l('add').$data['string']['item'];
    }else{
        $data['title'] = _l('new');
    }

    $this->load->view('translate_strings/add_edit', $data);
  }

  public function delete_translation($id = 0)
  {
    $string = $this->development_model->get_string($id);

    if (!$string) {
      show_404();
    }

    $success = $this->development_model->delete_string($id);

    if ($success == true) {
      set_alert('success', _l('deleted', _l('string')));
    } else {
      set_alert('warning', _l('problem_deleting', _l('string')));
    }

    redirect(admin_url('development/translate_strings'));
  }

  public function build_files(){
    $strings = $this->development_model->getAllStrings();
    $this->_build_unified($strings);
    set_alert('success', _l('updated_successfully', _l('development')));
    redirect('admin/development/translate_strings');

  }


  public function _build_test($strings){
    
    if (!file_exists(FCPATH.'modules/development/language/romanian')) {
      mkdir(FCPATH.'modules/development/language/romanian', 0777, true);
    }
    if (!file_exists(FCPATH.'modules/development/language/english')) {
      mkdir(FCPATH.'modules/development/language/english', 0777, true);
    }


    if (file_exists(FCPATH.'modules/development/language/romanian/unified_lang.php')) {
      unlink(FCPATH.'modules/development/language/romanian/unified_lang.php');
    }
    if (file_exists(FCPATH.'modules/development/language/english/unified_lang.php')) {
      unlink(FCPATH.'modules/development/language/english/unified_lang.php');
    }


    $line = '<?php';
    file_put_contents(FCPATH.'modules/development/language/romanian/unified_lang.php', $line.PHP_EOL , FILE_APPEND | LOCK_EX);
    file_put_contents(FCPATH.'modules/development/language/english/unified_lang.php', $line.PHP_EOL , FILE_APPEND | LOCK_EX);
    
    foreach($strings as $string){
      $line = "\$lang['".$string['item']."'] = '".htmlspecialchars($string['romanian'], ENT_QUOTES)."';";
      file_put_contents(FCPATH.'modules/development/language/romanian/unified_lang.php', $line.PHP_EOL , FILE_APPEND | LOCK_EX);
      $line = "\$lang['".$string['item']."'] = '".htmlspecialchars($string['english'], ENT_QUOTES)."';";
      file_put_contents(FCPATH.'modules/development/language/english/unified_lang.php', $line.PHP_EOL , FILE_APPEND | LOCK_EX);
    }

  }

  public function _build_unified($strings){
    
    if (!file_exists(APPPATH.'language/romanian')) {
      mkdir(APPPATH.'language/romanian', 0777, true);
    }
    if (!file_exists(APPPATH.'language/english')) {
      mkdir(APPPATH.'language/english', 0777, true);
    }

      if(!file_exists(APPPATH.'logs/lang')) {
          if(mkdir(APPPATH.'logs/lang', 0775, true)) {
              copy('uploads/index.html', APPPATH.'logs/lang/index.html');
          }
      }

      if (file_exists(APPPATH.'language/romanian/romanian_lang.php')) {
      copy(APPPATH.'language/romanian/romanian_lang.php', APPPATH.'logs/lang/romanian_lang.php.'.date('ymhhis'));
      unlink(APPPATH.'language/romanian/romanian_lang.php');
    }
    if (file_exists(APPPATH.'language/english/english_lang.php')) {
      copy(APPPATH.'language/english/english_lang.php', APPPATH.'logs/lang/english_lang.php.'.date('ymhhis'));
      unlink(APPPATH.'language/english/english_lang.php');
    }


    $line = '<?php';
    file_put_contents(APPPATH.'language/romanian/romanian_lang.php', $line.PHP_EOL , FILE_APPEND | LOCK_EX);
    file_put_contents(APPPATH.'language/english/english_lang.php', $line.PHP_EOL , FILE_APPEND | LOCK_EX);
    
    foreach($strings as $string){
      $line = "\$lang['".$string['item']."'] = '".htmlspecialchars($string['romanian'], ENT_QUOTES)."';";
      file_put_contents(APPPATH.'language/romanian/romanian_lang.php', $line.PHP_EOL , FILE_APPEND | LOCK_EX);
      $line = "\$lang['".$string['item']."'] = '".htmlspecialchars($string['english'], ENT_QUOTES)."';";
      file_put_contents(APPPATH.'language/english/english_lang.php', $line.PHP_EOL , FILE_APPEND | LOCK_EX);
    }

  }


    public function cards()
    {
        if (!has_permission('development', '', 'view')) {
            access_denied('development');
        }
        $data['title'] = _l('cards');

        $this->load->view('cards/manage', $data);
    }

    public function cards_datatable(){
        if (!has_permission('development', '', 'view')) {
            access_denied('development');
        }

        $this->load->model('development_model');

        $aColumns = [
            'id',
            'type_alert',
            'romanian',
            'english',
            'short_link',
        ];

        $sIndexColumn = 'id';
        $sTable       = db_prefix() . 'cards_assist';

        $where  = [];
        $filter = [];





        $result  = data_tables_init($aColumns, $sIndexColumn, $sTable, [], $where, ['id']);

        $output  = $result['output'];
        $rResult = $result['rResult'];

        foreach ($rResult as $aRow) {
            $row = [];
            $row[]  = $aRow['id'];
            $row[]  = '<div class="alert alert-bordered alert-'.$aRow['type_alert'].' p-5">'.$aRow['type_alert'].'</div>';
            $row[]  = '<span class="contentedt not-init" field="romanian" pk="'.$aRow['id'].'">'.$aRow['romanian'].'</span>';
            $row[]  = '<span class="contentedt not-init" field="english" pk="'.$aRow['id'].'">'.$aRow['english'].'</span>';


            //$row[]  = $aRow['romaniant'];
            $row[]  = $aRow['short_link'];


            $action
                = '<a type="button" class="btn btn-xs btn-outline-secondary" href="' . admin_url('development/edit_card/' . $aRow['id']) . '"><i class="fal fa-edit"></i></a>'
                . '<a type="button" class="btn btn-xs btn-danger mleft10" href="' . admin_url('development/delete_card/' . $aRow['id']) . '"><i class="fal fa-trash"></i></a>';

            $row[]              = $action;
            $output['aaData'][] = $row;
        }

        echo json_encode($output);
        die();
    }

    public function delete_card($id = 0)
    {
        $string = $this->development_model->get_card($id);

        if (!$string) {
            show_404();
        }

        $success = $this->development_model->delete_card($id);

        if ($success == true) {
            set_alert('success', _l('deleted', _l('string')));
        } else {
            set_alert('warning', _l('problem_deleting', _l('string')));
        }

        redirect(admin_url('development/cards'));
    }

    public function edit_card($id = null)
    {
        if (!has_permission('development', '', 'view')) {
            access_denied('development');
        }

        if ($this->input->post() && !$this->input->is_ajax_request()) {
            $data = $this->input->post();
            $this->form_validation->set_rules('english', _l('english'), 'required');
            if ($this->form_validation->run() === true) {
                if (!$id) {
                    $id = $this->development_model->add_card($data);

                    set_alert('success', _l('updated_successfully', _l('development')));

                } else {
                    $this->development_model->update_card($data, $id);
                    set_alert('success', _l('updated_successfully', _l('development')));
                }
                redirect(admin_url('development/edit_card/' . $id));
            }
        }elseif ($this->input->post() && $this->input->is_ajax_request()){
            $data = $this->input->post();
            $response = [];
            if (!$id) {
                $response['code'] = 'error';
                echo json_encode($response);exit;
            } else {
                $response['code'] = 'success';
                $this->development_model->update_card($data, $id);
                echo json_encode($response);exit;
            }
        }
        $data['string'] =  $this->development_model->get_card($id);

        if (!isset($data['id'])) $data['id'] = null;

        if (set_value('id', $data['id'] ?? null)){
            $data['title'] = _l('add').$data['string']['short_link'];
        }else{
            $data['title'] = _l('new_card');
        }

        $this->load->view('cards/add_edit', $data);
    }

}
