<?php

class BCard {
	public function __construct() {
		
		//$this->COMPANY_ID = $company_id;
	}

	public function GetConfigFile($company_id) {

		return $this->Get("*", "companies", "id =  '{$company_id}'", "id", "1", false, "obj");

	}

	public function Get($field, $table, $where="1=1", $order_by = "id", $limit = "25", $data_payload = false, $response='json') {
	
        if($order_by) $order_by =  "ORDER BY {$order_by}";
        if($limit) $limit = "LIMIT {$limit}";
         $sql = "SELECT $field FROM $table WHERE $where $order_by $limit";
      	
        if($response=='json') return sql_to_json($sql, FALSE,$data_payload);;
        if($response=='obj') {
        
            if($result = my_all($sql)) {

                $data = $result;
                return $data;
            }
    
		}
	}
	
	public function Query($sql, $data_payload = false, $response='json') {
	
      #	echo $sql; 
      	
        if($response=='json') return sql_to_json($sql, FALSE,$data_payload);;
        if($response=='obj') {
        
            if($result = my_all($sql)) {

                $data = $result;
                return $data;
            }
    
		}
	}

    

    public function GetScoutings($user_id, $where, $limit=25, $response='json'){

        $User  = $this->GetUser($user_id, 'obj');

        switch($User->role){
            case 'admin':
            case 'backoffice':
                $add_where = '';
            break;
            case 'team_leader':
                $team_view = '';
                if(!empty($User->team_member_ids)){
                    $team_view = "OR agent_id IN ($User->team_member_ids)";
                }
                $add_where = " AND (agent_id = '{$User->id}' {$team_view})";
            break;
            default:
                $add_where = " AND agent_id = '{$User->id}'";
            break;
        }
        
        //$PAGING = SQLPaging_limit($_REQUEST);
        if($limit) $PAGING = "LIMIT {$limit}";
        else {
            $PAGING = "LIMIT 25";
        }

        if($where) $add_where .= " AND {$where}";
    


       $sql = "SELECT * FROM scouting_view WHERE 1=1 {$add_where} AND company_id = ".COMPANY_ID." ORDER BY id DESC {$PAGING}";

        $sql_totals_filters = "SELECT count(*) as tot
       FROM scouting_view
       WHERE 1=1 {$add_where} 
       AND company_id = ".COMPANY_ID;


       $sql_totals = "SELECT count(*) as tot
       FROM scouting_view
       WHERE 1=1 {$add_where} 
       AND company_id = ".COMPANY_ID;


      $res = $this->Query($sql, false, 'obj');
      $res_totals_filters = $this->Query($sql_totals_filters, false, 'obj')[0]->tot;
      $res_totals = $this->Query($sql_totals, false, 'obj')[0]->tot;
       
        foreach($res as $sco){

            $sco->status_text = map_get_value('Potentials', 'scoutingstatus', $sco->status);
            $sco->zone_text = map_get_value('Potentials', 'opportunity_zone', $sco->zone_id);
            $sco->scouting_type_text = map_get_value('Potentials', 'scoutingtype', $sco->scouting_type);

        }

       if($response == 'ssp') {
        if(empty($res)) $res = [];
        $response = array(
            "iTotalRecords" => $res_totals,
            "iTotalDisplayRecords" => $res_totals_filters,
            "aaData" => $res
        );

            return $response;
        }

        if($response=='json') {
            return $json_gen = "{\"data\":" .json_encode($res). "}";
            

        }
        if($response=='obj') return $res;
    
    }
    
   
    public function GetPotential($id, $response='json'){
	
        $res = $this->Get('*', 'potentials_view', "id = '{$id}' AND company_id = '{$this->COMPANY_ID}'", 'id', 1);
      
        if($response=='json') return $res;
        if($response=='obj') return json_decode($res)[0];
	
	}
    
    

    public function GetMapValues($module, $field, $response='json'){
	
        $res = $this->Get('*', "array_map", "module = '{$module}' AND field = '{$field}'", 'id');
        if($response=='json') return $res;
        if($response=='obj') return json_decode($res)[0];
	
	}
	
	
	
	public function GetUser($id, $response='json'){
	
        $res = $this->Get('*, (SELECT GROUP_CONCAT(id) FROM users u2 WHERE team_leader_id = u1.id) as team_member_ids', 'users u1', "id = '{$id}' AND company_id = {$this->COMPANY_ID}", 'id', 1);
        
        if($response=='json') return $res;
        if($response=='obj') return json_decode($res)[0];
	
	}

    

	public function GetTargets($user_id, $response='json'){
	
        $res = $this->Get('*', 'targets', "user_id = '{$user_id}'", 'id', 50);
        
        if($response=='json') return $res;
        if($response=='obj') return json_decode($res);
	
	}

    public function GetCard($id, $response='json'){
	
        $res = $this->Get('*', 'cards_view', "id = '{$id}'", 'id', 1);
        
        if($response=='json') return $res;
        if($response=='obj') return json_decode($res)[0];
	
	}



    public function GetIdentity($id, $response='json'){
	
        $res = $this->Get('*', 'identities', "target_id = '{$id}'", 'id', 1);

	if($response=='json') return $res;
        if($response=='obj') return json_decode($res)[0];
	
	}

	public function GenerateVCard($object){

  if($object->img_url){
                $object->img_url_encoded = base64_encode(file_get_contents($object->img_url));
        } 

            $data = <<<EOD
BEGIN:VCARD
VERSION:3.0
FN;CHARSET=UTF-8:{$object->first_name} {$object->last_name}
N;CHARSET=UTF-8:{$object->last_name};{$object->first_name};;;
EMAIL;CHARSET=UTF-8;type=WORK,INTERNET:{$object->email}
TEL;TYPE=CELL:{$object->mobile}
TEL;TYPE=WORK,VOICE:{$object->phone}
TITLE;CHARSET=UTF-8:{$object->job_title}
ORG;CHARSET=UTF-8:{$object->company}
URL;CHARSET=UTF-8:{$object->website_url}
X-SOCIALPROFILE;TYPE=linkedin:{$object->in_url}
PHOTO;ENCODING=b;TYPE=PNG:{$object->img_url_encoded}
END:VCARD
EOD;
        return $data;
        
    }

    public function CreateCardToken($id){
	
        $CardData = $this->GetCard($id, 'obj');
        return dec_enc("encrypt", $CardData->id.'-'.$CardData->owner_id);
        
    }

    public function DecodeCardToken($string){
	
        $decrypt = dec_enc("decrypt", $string);
        $content = explode("-", $decrypt);

       return $CardData = $this->GetCard($content[0], 'obj');

    }
	
    public function Update($field_values, $table, $where="1=1") {
	
					
        $sql = "UPDATE  $table SET $field_values WHERE $where";

        return save_in_db($sql);
	}
	
	public function Delete($id, $table) {
	
         $sql = "DELETE FROM $table WHERE id = $id";
        return save_in_db($sql);
	}

    public function DeleteWhere($condition, $table) {
	
        $sql = "DELETE FROM $table WHERE {$condition}";
        return save_in_db($sql);
	}
    
    
	
	public function SoftDelete($id, $table, $status_field = 'status', $new_status = 0) {
	
					
     
        $sql = "UPDATE $table SET $status_field = '{$new_status}' WHERE id = $id AND company_id = {$this->COMPANY_ID}";
        return save_in_db($sql);
	}
	
	
	public function Insert($field_values, $table) {
	
					
        $sql = "INSERT INTO $table SET $field_values";
        return save_in_db($sql);
	}
	
	public function InsertOrUpdate($field_values, $table) {
				
         $sql = "INSERT INTO $table SET $field_values ON DUPLICATE KEY UPDATE {$field_values}";
        myb_log($sql, "MyB_IoU");
        return save_in_db($sql);
	}
	
   
    public function PrepSQLValues($array){
    $i = 0;
    foreach($array as $field => $value){
    
        $field = my_escape($field);
        $value = my_escape($value);
        if($value !== FALSE){
        if($i == 0){
                $sql = "{$field} = '{$value}'";
        } else {
            if(!empty($field)){
                $sql .= ", {$field} = '{$value}'";
            }
        }
        $i++;
        }
    }
    return $sql;
}


}
