Skip to content

Instantly share code, notes, and snippets.

@dexit
Last active July 29, 2025 12:18
Show Gist options
  • Select an option

  • Save dexit/ab43af98585972a26190fc96c364a3f1 to your computer and use it in GitHub Desktop.

Select an option

Save dexit/ab43af98585972a26190fc96c364a3f1 to your computer and use it in GitHub Desktop.
process_opportunity.php
<?php
// index.php
namespace ApiClient;
// Set global error handling for web requests
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//error_reporting(E_ALL);
error_reporting(E_ALL); // Use E_ALL for comprehensive error reporting
require_once './ApiClient/BaseApiClient.php';
require_once './ApiClient/PicsWebApiClient.php';
require_once './ApiClient/DynamicsApiClient.php';
require_once './ApiClient/WebhookApiClient.php';
require_once './ApiClient/YourlsApiClient.php';
require_once './ApiClient/NfceApiClient.php';
require_once './Handlers/LoggingHandler.php';
require_once './Handlers/DatabaseHandler.php';
require_once 'hubspot_functions.php';
require_once 'test.php';
use Dotenv\Dotenv;
use ApiClient\NfceApiClient;
use ApiClient\DynamicsApiClient;
use Handlers\LoggingHandler;
use Handlers\DatabaseHandler;
require __DIR__ . '/../../vendor/autoload.php';
//$trace = debug_backtrace();
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$logConfig = [
'file' => $_ENV['LOG_FILE'],
'json_file' => $_ENV['LOG_JSON_FILE'],
'json_logging_enabled' => filter_var($_ENV['JSON_LOGGING_ENABLED'], FILTER_VALIDATE_BOOLEAN),
];
$dbConfig = [
'host' => $_ENV['DB_HOST'],
'dbname' => $_ENV['DB_NAME'],
'user' => $_ENV['DB_USER'],
'password' => $_ENV['DB_PASSWORD'],
];
$yourlsApiUrl = $_ENV['YOURLS_API_URL'];
$yourlsApiKey = $_ENV['YOURLS_API_KEY'];
$logger = new LoggingHandler($logConfig);
$databaseHandler = $_ENV['DB_LOGGING_ENABLED'] === 'true' ? new DatabaseHandler($dbConfig) : null;
//$templates = $_ENV['DB_LOGGING_ENABLED'] === 'true' ? $databaseHandler->getTemplate('default_template') : null;
//if (!$templates) {
//die('Email templates not found.');
//}
// Add DB logging with raw_incoming_logs
$loggingHandler = new LoggingHandler($logConfig);
$databaseHandler = $_ENV['DB_LOGGING_ENABLED'] === 'true' ? new DatabaseHandler($dbConfig) : null;
$nfceApiClient = new NfceApiClient($loggingHandler, $databaseHandler);
//$dynamicsClientApi = new DynamicsApiClient($logger, $databaseHandler);
$dynamicsClientApi = new DynamicsApiClient($logger, $databaseHandler);
// PHP 8.3: Security Headers
//header('X-Content-Type-Options: nosniff');
header('Content-Type: text/html; charset=utf-8'); // Default for form handler, can be overridden by API endpoints
// Route requests
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['opp'])) {
// Handle Dynamics-triggered workflow
//require __DIR__ . '/get_opp_by_oppref.php';
$oppRef = $_GET['opp'] ?? null;
// lookup dynamics, then get data for NCFE
$selectColumns = '$select=active_ncfeuser,active_ncfeassessments,active_ncfemodules,active_ncferoles,active_ncfegroups,active_courseinfo,active_opportunityref,active_skillsforwardaccountcreated,active_iduserinstitution,active_iduser,active_leadreferenceid,firstname,lastname,emailaddress1,active_fundingstream,address1_postalcode,mobilephone,telephone1,birthdate';
$filter = "$filter=active_opportunityref eq '$oppRef'";
$response = $dynamicsClientApi->getOpportunityById($selectColumns, $filter);
$opportunity = $response->value[0];
// opp result
if ($opportunity) {
// Process the opportunity data as needed
// For example, you can log it or pass it to a view
$logger->logInfo("Opportunity data retrieved successfully.", ['opportunity' => $opportunity]);
// Extract relevant data for NCFE user registration
$firstName = $opportunity->firstname ?? '';
$lastName = $opportunity->lastname ?? '';
$email = $opportunity->emailaddress1 ?? '';
$postcode = $opportunity->address1_postalcode ?? '';
$phone1 = $opportunity->mobilephone ?? '';
$dob = isset($opportunity->birthdate) ? date('Y-m-d', strtotime($opportunity->birthdate)) : null;
$studentRef = $opportunity->active_leadreferenceid ?? $oppRef;
$courseInfo = $opportunity->active_courseinfo ?? '';
$oppRef = $opportunity->active_opportunityref ?? '';
$skillsForwardAccountCreated = $opportunity->active_skillsforwardaccountcreated ?? false;
$idUserInstitution = $opportunity->active_iduserinstitution ?? '';
$idUser = $opportunity->active_iduser ?? '';
$activeFundingStream = $opportunity->active_fundingstream ?? '';
$activeNcfeAssessments = $opportunity->active_ncfeassessments ?? '';
$activeNcfeModules = $opportunity->active_ncfemodules ?? '';
$activeNcfeRoles = $opportunity->active_ncferoles ?? '';
// full guid opportunity id
$activeOpportunityId = $opportunity->active_opportunityid ?? '';
$activeNcfeGroups = $opportunity->active_ncfegroups ?? '';
// 0 by default, 1 - this is us, 2, 3
$activeNcfeUsers = $opportunity->active_ncfeusers ?? '1';
} else {
$logger->logError("No opportunity found for the given reference.", ['oppRef' => $oppRef]);
exit;
}
// Generate a simple username and password
$username = $email; //strtolower(str_replace(' ', '', $firstName)) . '.' . strtolower(str_replace(' ', '', $lastName)) . '_' . uniqid();
$password = bin2hex(random_bytes(8)); // 16 character hex string
$registerUserData = [
'firstName' => $firstName,
'lastName' => $lastName,
'email' => $email,
'username' => $username,
'password' => [
'password' => $password,
'format' => 'plain'
],
'studentRef' => $studentRef,
'sendWelcomeEmail' => false, // Set to true if you want NCFE to send welcome email
'phone1' => $phone1,
'dob' => $dob,
'postcode' => $postcode,
];
$registerUserResponse = $nfceApiClient->registerUser($registerUserData);
if ($registerUserResponse && $registerUserResponse['code'] === 200) {
$logger->logInfo("NCFE user registered successfully.", ['user' => $registerUserResponse['data']]);
$idUser = $registerUserResponse['data']['idUser'];
$idUserInstitution = $registerUserResponse['data']['idUserInstitution'];
$skillsForwardAccountCreated = true; // Assuming account creation was successful
} else {
$logger->logError("Failed to register NCFE user.", ['response' => $registerUserResponse]);
echo "<h1>Error registering NCFE user</h1>";
exit;
}
// Fetch user details from NCFE from email used in reg
$ncfeUserDetailsResponse = $nfceApiClient->getUserDetail(['email' => $email]);
if ($ncfeUserDetailsResponse && $ncfeUserDetailsResponse['code'] === 200) {
$ncfeUserDetails = $ncfeUserDetailsResponse['data'];
$logger->logInfo("NCFE user details retrieved successfully.", ['userDetails' => $ncfeUserDetails]);
// Prepare data for the view
$viewData = [
'firstName' => $firstName,
'lastName' => $lastName,
'email' => $email,
'username' => $username,
'password' => $password,
'studentRef' => $studentRef,
'courseInfo' => $courseInfo,
'oppRef' => $oppRef,
'active_opportunityid' => $activeOpportunityId,
'skillsForwardAccountCreated' => $skillsForwardAccountCreated,
'idUserInstitution' => $idUserInstitution,
'idUser' => $idUser,
'activeFundingStream' => $activeFundingStream,
'activeNcfeAssessments' => $activeNcfeAssessments,
'activeNcfeModules' => $activeNcfeModules,
'activeNcfeRoles' => $activeNcfeRoles,
'activeNcfeGroups' => $activeNcfeGroups,
'activeNcfeUsers' => $activeNcfeUsers,
'phone1' => $phone1,
'dob' => $dob,
'postcode' => $postcode,
];
// Render the view (you can use a templating engine or simple HTML)
echo "<h1>NCFE User Registration</h1>";
echo "<p>First Name: {$viewData['firstName']}</p>";
echo "<p>Last Name: {$viewData['lastName']}</p>";
echo "<p>Email: {$viewData['email']}</p>";
echo "<p>Username: {$viewData['username']}</p>";
echo "<p>Password: {$viewData['password']}</p>";
echo "<p>Student Reference: {$viewData['studentRef']}</p>";
echo "<p>Course Info: {$viewData['courseInfo']}</p>";
echo "<p>Opportunity Reference: {$viewData['oppRef']}</p>";
echo "<p>Skills Forward Account Created: " . ($viewData['skillsForwardAccountCreated'] ? 'Yes' : 'No') . "</p>";
echo "<p>ID User Institution: {$viewData['idUserInstitution']}</p>";
echo "<p>ID User: {$viewData['idUser']}</p>";
echo "<p>Active Funding Stream: {$viewData['activeFundingStream']}</p>";
echo "<p>Active NCFE Assessments: {$viewData['activeNcfeAssessments']}</p>";
echo "<p>Active NCFE Modules: {$viewData['activeNcfeModules']}</p>";
echo "<p>Active NCFE Roles: {$viewData['activeNcfeRoles']}</p>";
echo "<p>Active NCFE Groups: {$viewData['activeNcfeGroups']}</p>";
echo "<p>Active NCFE Users: {$viewData['activeNcfeUsers']}</p>";
echo "<p>Active Opportunity ID: {$viewData['active_opportunityid']}</p>"; // Add this line to display activeOpportunityId
} elseif ($ncfeUserDetailsResponse && $ncfeUserDetailsResponse['code'] == 200) {
$logger->logError("Failed to retrieve NCFE user details.", ['response' => $ncfeUserDetailsResponse]);
echo "<h1>Error retrieving NCFE user details</h1>";
} else {
echo "<h1>Error retrieving NCFE user details</h1>";
}
// update opportunity with NCFE user details userinstitution and skillsforwardaccountcreated to true
// $updateData = [
// 'active_skillsforwardaccountcreated' => $skillsForwardAccountCreated,
// 'active_iduserinstitution' => $idUserInstitution,
// 'active_iduser' => $idUser,
// ];
// Log processing step: Update Dynamics Opportunity
$dynamicsUpdateData = [
'active_ncfeuser' => true,
'active_iduser' => (string)$idUser,
'active_iduserinstitution' => (string)$idUserInstitution,
'active_skillsforwardaccountcreated' => true,
// 'active_ncfegroups' => json_encode([]), // Assuming no groups assigned by this process directly
// 'active_ncfeassessments' => json_encode($finalAssignedDiags), // Using 'active_ncfeassessments' for diagnostics
// 'active_ncfemodules' => json_encode($finalAssignedModules),
// 'active_ncferoles' => json_encode([]), // If roles are tracked in Dynamics
];
$patchSuccess = $dynamicsClientApi->patchOpportunityById($activeOpportunityId, $dynamicsUpdateData);
if ($patchSuccess) {
$logger->logInfo("Dynamics Opportunity updated with NCFE user details.", ['activeOpportunityId' => $activeOpportunityId, 'data' => $dynamicsUpdateData]);
echo '<h1>Dynamics Opportunity updated successfully</h1>';
echo '<p>Active Opportunity ID: ' . htmlspecialchars($activeOpportunityId) . '</p>';
} else {
$logger->logError("Failed to update Dynamics Opportunity with NCFE user details.", ['activeOpportunityId' => $activeOpportunityId, 'data' => $dynamicsUpdateData]);
echo '<h1>Error updating Dynamics Opportunity</h1>';
}
}elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['webservicepassword'])) {
if($_GET['webservicepassword'] == 'NCFE'){
// recieved a WEBHOOK from NCFE
// original request as seen ion logs : https://webhook.site/7e99cf15-bbc9-4c0a-ac2f-7ee380bef5b2/api/result/addScreener?webservicepassword=&json_ForskillsUser=%7B%22idUser%22%3A%227674172%22%2C%22idUserInst%22%3A%224720068%22%2C%22idInstitution%22%3A%226351%22%2C%22username%22%3A%22zzzrvath%22%2C%22studentRef%22%3A%22%22%2C%22firstname%22%3A%22Milan%22%2C%22lastname%22%3A%22Horvath%22%2C%22email%22%3A%22zzzzrvath1989%40outlook.com%22%7D&json_Screener=%7B%22idAssessmentUser%22%3A%2229690506%22%2C%22idUserDiagnostic%22%3A%228906992%22%2C%22idUserInst%22%3A%224720068%22%2C%22course%22%3A%22FS+Assessments%22%2C%22diagnostic%22%3A%22FS+English+Assessment%22%2C%22assessment%22%3A%22FS+English+Screening%22%2C%22level%22%3A%22Entry+Level+1%22%2C%22date%22%3A%222025-07-25+14%3A50%3A30%22%2C%22timeTaken%22%3A%2231%22%7D
// /api/result/addScreener needs to be parsed, and used to determine what action is taken place:
// /api/result/ -> method = addScreener
// webservicepassword = NCFE
// json_ForskillsUser = {"idUser":"7100002","idUserInst":"4000068","idInstitution":"6301","username":"zzzath","studentRef":"","firstname":"Milan","lastname":"Zorvath","email":"[email protected]"}
// json_Screener = {"idAssessmentUser":"29690506","idUserDiagnostic":"8906992","idUserInst":"4720068","course":"FS Assessments","diagnostic":"FS English Assessment","assessment":"FS English Screening","level":"Entry Level 1","date":"2025-07-25 14:50:30","timeTaken":"31"}
$ncfeMethod = ''; // pars ethe request url as descirbe above about api/result.
$json_ForskillsUser = $_GET['json_ForskillsUser']; // parse this so its accesible
$json_Screener = $_GET['json_Screener']; // parse this so its accesible
// find the idUser in Dynamics -> search by either active_userid ? = idUser or email, to update with the Screener data
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
// Handle general API proxy requests (from forms or other POSTs)
// require __DIR__ . '/post_api_by_action.php';
} else {
// Default for other GET requests (e.g., initial page load to display forms)
// require __DIR__ . '/api_form_handler.php';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment