<?php
session_start();
$currentBaseDir = dirname($_SERVER['PHP_SELF']);
include($_SESSION['basedir']."core.php");

$svaTool = new svaTool();

//print_r($_REQUEST); 


$errorCode = 0;

$password = NULL;
$confPasswd = NULL;
// Ajout de nouvel utilisateur

if (isset($_REQUEST['callReasonType']) && $_REQUEST['callReasonType'] != "-1")
    $callReasonType = addslashes($_REQUEST['callReasonType']);
else
    $errorCode = 1;

if (isset($_REQUEST['csrDetails']) && strlen($_REQUEST['csrDetails'])>0 )
    $csrDetails = addslashes($_REQUEST['csrDetails']);
else
    $errorCode = 2;

if (isset($_REQUEST['csrComment']) && strlen($_REQUEST['csrComment'])>0 )
    $csrComment = addslashes($_REQUEST['csrComment']);
else
    $errorCode = 3;
	

if (isset($_REQUEST['firstName']) && strlen($_REQUEST['firstName'])>0 )
    $firstName = addslashes($_REQUEST['firstName']);
else
    $errorCode = 5;
	
if (isset($_REQUEST['company']) && strlen($_REQUEST['company']) >0 )
    $company = addslashes($_REQUEST['company']);
else
    $errorCode = 6;
	
// Vérification de l'email uniquement s'il est renseigné
if (!empty($_REQUEST['emailId'])) {
    if (filter_var($_REQUEST['emailId'], FILTER_VALIDATE_EMAIL)) {
        $emailId = addslashes($_REQUEST['emailId']);
    } else {
        $errorCode = 7; 
    }
} else {
    $emailId = ""; // Assigne une valeur vide si aucun email n'est fourni
}
/*
if (isset($_REQUEST['callerNumber']) && strlen($_REQUEST['callerNumber'])>0 && is_numeric($_REQUEST['callerNumber']) )
    $callerNumber = addslashes($_REQUEST['callerNumber']);
else
    $errorCode = 8;
	*/
	



$csrId = addslashes($_REQUEST['csrId']);
$callerId = addslashes($_REQUEST['callerId']);
$firstName = addslashes($_REQUEST['firstName']); 
$lastName = addslashes($_REQUEST['lastName']);

//$address = addslashes($_REQUEST['address']);
$mobileNumber = addslashes($_REQUEST['mobileNumber']);
$emailId = addslashes($_REQUEST['emailId']);
$callId = addslashes($_REQUEST['callId']);
$userId = $_SESSION['ownerId'];
$statut = addslashes($_REQUEST['operationId']);
$actionType = addslashes($_REQUEST['actionType']);
$callType = addslashes($_REQUEST['callType']);




//$companyPart = explode("[", $company);

//$company = str_replace("]","",$companyPart[1]);


/************* Nouvelles données ***********/

 $callModule = addslashes($_REQUEST['callModule']);


$submodule = addslashes($_REQUEST['submodule']);

/**** Nouvelle variable ****/

if (isset($_REQUEST['objet']) && strlen($_REQUEST['objet'])>0 ) 

    $objet = addslashes($_REQUEST['objet']);
else
    $errorCode = 11;

if (isset($_REQUEST['incident']) && strlen($_REQUEST['incident'])>0 ) 

    $incident = addslashes($_REQUEST['incident']);
else
    $errorCode = 12;

if (isset($_REQUEST['analysePlainte']) && strlen($_REQUEST['analysePlainte'])>0 )
    $analysePlainte = addslashes($_REQUEST['analysePlainte']);
//else
   // $errorCode = 1;

    if (isset($_REQUEST['decision']) && strlen($_REQUEST['decision'])>0 )
    $decision = addslashes($_REQUEST['decision']);
//else
   // $errorCode = 9;

$formId= $_REQUEST['formId'];







if ($errorCode == 0) {
$id = 0;
$field[0] = date('Y-m-d H:i:s');
$field[1] = '';
$field[2] = '';
$field[3] = '';
$field[4] = '';
$callerNumber = null;
$csrId = $dba->getCSRID("crm");
$agencyName = $dba->getSCCAgencyByUserId( $userId );
$res = $dba->AddTicketExtend(1, $firstName, $lastName, $callId, $userId, $csrId, $callerId, $company, $company, $mobileNumber, $emailId, $callReasonType, $csrDetails,$callType, $actionType,$customerType , $agencyName, $callModule, $submodule, $callprority, $formId) ;

$customerName = $firstName." ".$lastName ;
$dba->UpdateAddSCCCustomer(0,0,$firstName, $lastName, $mobileNumber, "", $company, $emailId,$field);
$dba->UpdateAddComment($id, $userId, $csrId, $csrDetails, 0, $customerName,0 );
sleep(1);
$dba->UpdateAddComment($id, $userId, $csrId, $csrComment, 1, $customerName,0 );
//var_dump($statut);

$dba->UpdateCallHistory($callId, $statut );
$dba->UploadTicketHistory( $userId, $profileId , $csrId, $type, $comment, $actionType);

$dba->UpdateAddDelMugefciSupInfoPrestataire(0, 0, $csrId, $objet, $incident, $decision, $analysePlainte, 0);

   //$errorCode = 10;

   if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    
    
    $originalFileName = basename($_FILES['file']['name']);
    $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION); // Récupérer l'extension
    $fileBaseName = pathinfo($originalFileName, PATHINFO_FILENAME); // Récupérer le nom sans extension

    // Remplacer les espaces par des underscores
    $fileBaseName = preg_replace('/\s+/', '_', $fileBaseName);

    //date('dmY_His')
    $currentDate = date('dmY');
    $newFileName = "{$fileBaseName}_{$currentDate}.{$fileExtension}";

    $uploadFilePath = $uploadDir . $newFileName;

    // Déplacer le fichier téléchargé
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath)) {
         // Enregistrement du fichier dans la base de données
       //  $uploadResult = $dba->UploadTicketFiles($newFileName, $uploadFilePath, $ticketId);
       $uploadResult = $dba->UploadTicketFiles($newFileName, $uploadFilePath, $csrId);
       $fileAttachments[] =$uploadFilePath; // ici aussi
       // $errorMessage = "Fichier téléchargé avec succès sous le nom : {$newFileName}";
    } else {
        $errorCode = 14;
       
    }
} else if (isset($_FILES['file'])) {
    $errorCode =15;
}


// Ajouter le chemin absolu pour les attachements

/*commence ici */
    $absoluteAttachments = array_map(function($filePath) {
    return "/opt/svam/var/www/gui/manager/products/scc/" . $filePath;
}, $fileAttachments);
    
     

    // Notification du ticket au mutualiste
    
        $subject = "AVIS DE CREATION DU TICKET  N° " . $csrId. " [ ".$csrDetails." ] ";
        $ccList = $emailId ;
        $ccList = rtrim($ccList, ",");
        $attachments = implode(",", $absoluteAttachments); //attache les fichiers selectionnés ici 
  
        
        
        $resSla =  $dba->getSLABySubMenuId( $submodule);
        
        $userres = $dba->getUserDetailById($userId);
       // print_r($userres);
        $agentName = $userres[0]['first_name_v'] . " " . $userres[0]['last_name_v'];
       // echo $agentName;
        $moduleres = $dba->getSCCModules($callModule);
        $submoduleres =  $dba->getSCCSubModules($submodule);
    
      
       $content = $svaTool->prepareMailBodyTicketCreationPrestataire($csrId, $lastName, $agentName, $csrDetails, $moduleres[0]['motif_name_v'], $submoduleres[0]['motif_name_v'], $resSla[0]['sla_duration_n']);
        
        $dba->SCCUploadMailNotification("reclamation@mugef-ci.com", $ccList, $subject, $content, $attachments); 
    //echo $content;
  // Fin envoie du ticket

}




switch ($errorCode) {

    case 0 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"TICKET CREE AVEC SUCCES !\"  }"; 
        break;
    case 1 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ ENTRER ANALYSE DE LA PLAINTE !\"  }";
        break;
    /*case 10 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ SELECTIONNER LE MODULE !\"  }";
        break; */
    case 2 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ DETAILLER LA REQUETE DU CLIENT !\"  }"; 
        break;
    case 3 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ INSERER UN COMMENTAIRE SUR LE TICKET.\"  }"; 
        break;
	case 4 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ ENTRER LE NUMERO DE L'APPELANT.\"  }";
        break;
    case 5 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! LE NOM DU PRESTATAIRE  EST INVALIDE.\"  }"; 
        break;
    case 6 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ SAISIR LA RAISON SOCIALE.\"  }";
        break;
    case 7 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! L'EMAIL  EST INVALIDE.\"  }";
        break;
	case 8 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! LE NUMERO APPELANT EST INVALIDE !\"  }";
        break;
	case 9 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ ENTRER LA DECISION !\"  }";
        break;
    case 11 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ ENTRER OBJET !\"  }";
        break;
    
    case 12 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ ENTRER LA PERIODE DE INCIDENT !\"  }";
        break;
 /*   case 4 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ SELECTIONNER LA STRATEGIE DES APPELS ENTRANTS.\"  }";
        break;
   /* case 5 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! LE LOGIN EST INVALIDE.\"  }"; 
        break;
    case 6 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! L'EMAIL EST INVALIDE.\"  }";
        break;
    /*case 7 : $msg =  "ERREUR ! LE MOT DE PASSE EST INVALIDE.";
        break;
    case 8 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! LE MOT DE PASSE DE CONFIRMATION EST INVALIDE .!\"  }"; 
        break;
    case 9 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! LES MOTS DE PASSE NE CONCORDENT PAS.\"  }";
        break; */
    case 13 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! IMPOSSIBLE DE CREER LE COMPTE. VEUILLEZ RE-ESSAYER ULTERIEUREMENT!\"  }";  break;
    case 14: $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! UN PROBLEME LORS DE ENREGISTREMENT DU FICHIER SELECTIONNE !\"  }";
    break;
case 15: $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! AUCUN FICHIER N'A ÉTÉ TÉLÉCHARGÉ .\"  }";
    break;

	/*
		case 14 : $msg = "{ \"errorCode\": $errorCode,\"errorMessage\" :\"ERREUR ! VEUILLEZ SELECTIONNER LE PLAN TARIFAIRE ASSOCIE AU COMPTE !\"  }";   break; */
   
	 
}


echo $msg ;


?>