<?php
chdir('../');
require_once 'autoload.php';

$admin = new admin_controller;
$session = new session;
$uni = new university_controller;
$payment_gateways = new payment_gateways_controller;

$students = new students_controller;
$exam_enrollments = new exam_enrollments_controller;
$payments = new payments_controller;

$info = $uni->index();
$gateways = $payment_gateways->index();
date_default_timezone_set($info['timezone']);

if ($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['response'])) {

foreach ($gateways as $value) {
$details = unserialize($value['details']);
}

$reference  = $_GET['response'];
$base       = 'https://api.lenco.co/access/v2/';
$secret_key = $details['secret_key'];

$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $base . "collections/status/$reference",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $secret_key",
"accept: application/json",
"content-type: application/json"
],
]);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
echo "cURL Error #: " . $err;
exit;
}

$data = json_decode($response, true);

$ref = $_SESSION['application']['reference'];

$std_data = [
'id' => time(),
'student_number' => $_SESSION['application']['student_number'],
'first_name' => $_SESSION['application']['first_name'],
'last_name' => $_SESSION['application']['last_name'],
'dob' => $_SESSION['application']['dob'],
'nrc' => $_SESSION['application']['nrc'] ?? null,
'passport_no' => $_SESSION['application']['passport_no'] ?? null,
'nationality' => $_SESSION['application']['nationality'],
'city_town' => $_SESSION['application']['city'],
'birth_place' => $_SESSION['application']['birthplace'],
'telephone' => $_SESSION['application']['telephone'],
'whatsapp_no' => $_SESSION['application']['whatsapp_no'] ?? null,
'email_address' => $_SESSION['application']['email_address'],
];

$enroll_data = [
'student_id' => $std_data['id'],
'programme_id' => $_SESSION['application']['programme_id'],
'exam_type_id' => $_SESSION['application']['exam_type'],
'exam_session_id' => $_SESSION['application']['session'],
'courses' => serialize($_SESSION['application']['courses']),
'create_date' => date('Y-m-d H:i:s'),
'reference_no' => $ref,
];

$payment_data = [
'payment_method' => 1,
'reference_no' => $ref,
'amount' => $_SESSION['application']['total'],
'payment_date' => date('Y-m-d H:i:s'),
'callback_data' => $response,
];

$students->store($std_data);
$exam_enrollments->store($enroll_data);
$payments->store($payment_data);

unset($_SESSION['application']);

header("Location: ../docket?ref=$ref");
exit;

} else {
header("Location: ../");
exit;
}

?>
