<?php

/*Este script es para relacionar aquellos contactos con sus cuentas en la tabla vtiger_crmentityrel 

Busca y relaciona contactos que tengan cuentas pero que no estén asociadas a nivel del CRM.
*/

require_once 'data/CRMEntity.php';
include_once 'includes/main/WebUI.php';
include_once 'vtlib/Vtiger/Module.php';
require_once 'includes/Loader.php';
require_once 'include/utils/utils.php';

vimport('includes.http.Request');
vimport('includes.runtime.Globals');
vimport('includes.runtime.BaseModel');
vimport ('includes.runtime.Controller');
vimport('includes.runtime.LanguageHandler');

ini_set('max_execution_time', 0);
set_time_limit(0);

global $adb, $current_user,$HELPDESK_SUPPORT_EMAIL_ID, $HELPDESK_SUPPORT_NAME, $curtime;
$current_user->id = 1;

$SQL = "SELECT DISTINCT vtiger_crmentity.crmid, vtiger_contactdetails.firstname, vtiger_contactdetails.lastname, vtiger_contactdetails.phone, vtiger_contactdetails.email, vtiger_contactdetails.mobile, vtiger_contactdetails.accountid, vtiger_crmentity.smownerid, vtiger_account.accountname, vtiger_crmentity.source, ( SELECT COUNT(vtiger_crmentityrel.relcrmid) FROM vtiger_crmentityrel WHERE vtiger_crmentityrel.relcrmid = vtiger_crmentity.crmid) n, ( SELECT COUNT(vtiger_crmentityrel.relcrmid) FROM vtiger_crmentityrel WHERE vtiger_crmentityrel.crmid = vtiger_crmentity.crmid) n2 
FROM vtiger_contactdetails 
INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid 
INNER JOIN vtiger_account ON vtiger_account.accountid = vtiger_contactdetails.accountid 
WHERE vtiger_crmentity.deleted = 0 having n <1 && n2<1";

$resultQuery = $adb->pquery($SQL,[]);
$nResult = $adb->num_rows($resultQuery);

echo "Se encontraron <b>".$nResult."</b> contactos sin asociar.<br>";


if(!empty($nResult))
{
    echo "Asociando Contactos: <br />";

    for ($i=0; $i < $nResult; $i++) { 
       $row = $adb->query_result_rowdata($resultQuery,$i);
       $contactId = $row['crmid'];
       $accountId = $row['accountid'];
       $adb->pquery("INSERT INTO vtiger_crmentityrel values (?,?,?,?)",[$accountId,'Accounts',$contactId,'Contacts']);
    
       echo "<pre>"; print_r(array_map('decode_html',$row)); echo "</pre>";

    }
}





