<?php
header('Content-Type: application/json');

// Detect content type
$contentType = $_SERVER["CONTENT_TYPE"];

if (stripos($contentType, 'application/json') !== false) {
    $data = json_decode(file_get_contents("php://input"), true);
} else {
    $data = $_POST; // fallback
}

// Basic validation
if (!isset($data['testId'], $data['email'], $data['name'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

// Optional: Extract additional fields
$testId = $data['testId'];
$email = $data['email'];
$name = $data['name'];
$score = $data['score'];
$status = $data['status'];
$reportUrl = $data['reportUrl'];

// 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
(test_id, email, name, score, status, report_url, received_at)
VALUES
('$testId', '$email', '$name', '$score', '$status', '$reportUrl', now())
";

// 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)]);
}

// Log for debugging
file_put_contents("imocha_callback_log.txt", date("Y-m-d H:i:s") . "\n" . print_r($data, true) . "\n", FILE_APPEND);

// Respond with success
http_response_code(200);
echo json_encode(["status" => "received"]);
?>
//<?php
//header('Content-Type: application/json');
//
//// === Step 1: Capture raw input ===
//$contentType = isset($_SERVER["CONTENT_TYPE"]) ? $_SERVER["CONTENT_TYPE"] : '';
//$data = [];
//
//if (stripos($contentType, 'application/json') !== false) {
//    $rawInput = file_get_contents("php://input");
//    $data = json_decode($rawInput, true);
//} else {
//    $data = $_POST;
//    $rawInput = json_encode($_POST);
//}
//
//// === Step 2: Log the incoming request for debugging ===
//$logData = "==== Callback Received at " . date("Y-m-d H:i:s") . " ====\n";
//$logData .= "Content-Type: $contentType\n";
//$logData .= "Raw Input:\n" . $rawInput . "\n";
//$logData .= "Parsed Data:\n" . print_r($data, true) . "\n\n";
//
//file_put_contents("imocha_callback_log.txt", $logData, FILE_APPEND);
//
//// === Step 3: Extract values safely ===
//$testId = isset($data['testId']) ? $data['testId'] : null;
//$email = isset($data['email']) ? $data['email'] : null;
//$name = isset($data['name']) ? $data['name'] : null;
//$score = isset($data['score']) ? $data['score'] : null;
//$status = isset($data['status']) ? $data['status'] : null;
//
//// === Step 4: Optional - Save to DB ===
//// Uncomment and use this only after confirming the fields from log
///*
//include "../config/database.php";
//
//if ($testId && $email && $name && $score && $status) {
//    $stmt = $conn->prepare("INSERT INTO imocha_results (test_id, email, name, score, status, received_at) VALUES (?, ?, ?, ?, ?, NOW())");
//    $stmt->bind_param("sssss", $testId, $email, $name, $score, $status);
//    $stmt->execute();
//    $stmt->close();
//}
//*/
//
//// === Step 5: Final Response ===
//http_response_code(200); // Always return 200 to prevent retries from iMocha
//echo json_encode(["status" => "received"]);
//?>