<?php
// assessment/imocha-callback.php

// 1. Read the raw POST input
$body = file_get_contents("php://input");
$data = json_decode($body, true);

// 2. (Optional) Log to a file for debugging
file_put_contents("callback_log.txt", print_r($data, true), FILE_APPEND);

// 3. Basic validation
if (!isset($data['CandidateEmailId'], $data['Status'])) {
    http_response_code(400);
    echo json_encode(['status' => 'Invalid payload']);
    exit;
}

// 4. Extract important fields
$candidateEmail = $data['CandidateEmailId'];
$status = $data['Status'];
$totalScore = $data['TotalScore'] ?? 0;
$candidateScore = $data['CandidateScore'] ?? 0;
$reportUrl = $data['ReportPDFUrl'] ?? null;
$testId = $data['TestInvitationId'];
$performance = $data['PerformanceCategory'] ?? null;
$attemptedUtc = $data['AttemptedOnUtc'] ?? null;

// Save to DB
include "../config/database.php";
include '../config/properties.php';

$servername = HOST;
$username = USER;
$password = PASSWORD;
$dbname = DATABASE;
$learner_path = CLIENT_HTTP_PATH;
$app_path = $properties['jdbc.playstore_link'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// Turn autocommit off
$conn->autocommit(FALSE);


$sql = "INSERT INTO imocha_results
(email, test_id, status, score, total, report_url, performance, attempted_on_utc)
VALUES
('$candidateEmail', '$testId', '$status', '$candidateScore', '$totalScore', '$reportUrl', '$performance', '$attemptedUtc')
ON DUPLICATE KEY UPDATE
  status = '$status',
  score = '$candidateScore',
  total = '$totalScore',
  report_url = '$reportUrl',
  performance = '$performance',
  attempted_on_utc = '$attemptedUtc'";

// Execute
if (mysqli_query($conn, $sql)) {
    http_response_code(200);
    echo json_encode(['status' => 'received']);
} else {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => mysqli_error($conn)]);
}

// 6. Send success response
http_response_code(200);
?>
