<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *"); // Allow requests from any origin (adjust if needed for security)
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// --- Include Database Connection ---
require_once 'db.php'; // This makes the $conn (mysqli object) available
// ------------------------------------

// Function to send JSON response
function send_json_response($status, $message, $data = null) {
    // Ensure connection is closed before exiting if it exists
    global $conn;
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
    http_response_code($status === 'success' ? 200 : 400); // Use 200 for success, 400 for client errors
    echo json_encode(['status' => $status, 'message' => $message, 'data' => $data]);
    exit;
}

// 1. Check Request Method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Note: db.php might have already exited on connection error,
    // but we keep this check for completeness. send_json_response handles closing.
    send_json_response('error', 'Invalid request method. Only POST is allowed.');
}

// 2. Receive Data (expecting JSON payload)
$raw_data = file_get_contents("php://input");
if (!$raw_data) {
    send_json_response('error', 'No data received.');
}

// 3. Decode JSON
$data = json_decode($raw_data, true); // true for associative array

if (json_last_error() !== JSON_ERROR_NONE) {
    send_json_response('error', 'Invalid JSON format: ' . json_last_error_msg());
}

// 4. Validate Data
$user_id = $data['user_id'] ?? null;
$video_id = $data['video_id'] ?? null;
$event_type = $data['event_type'] ?? null;
$timestamp_offset = $data['timestamp_offset'] ?? null; // Can be 0, so check for null specifically

$allowed_event_types = ['play', 'pause', 'rewind', 'forward'];

if (empty($user_id) || !is_numeric($user_id)) {
    send_json_response('error', 'Missing or invalid user_id.');
}
if (empty($video_id) || !is_numeric($video_id)) {
    send_json_response('error', 'Missing or invalid video_id.');
}
if (empty($event_type) || !in_array($event_type, $allowed_event_types)) {
    send_json_response('error', 'Missing or invalid event_type. Must be one of: ' . implode(', ', $allowed_event_types));
}
if ($timestamp_offset === null || !is_numeric($timestamp_offset)) {
     // Allow 0 but not null or non-numeric
    send_json_response('error', 'Missing or invalid timestamp_offset.');
}

// Convert types just in case (mysqli bind_param handles this mostly, but good practice)
$user_id = (int) $user_id;
$video_id = (int) $video_id;
$timestamp_offset = (int) $timestamp_offset;

// 5. Prepare SQL Statement (using mysqli)
$sql = "INSERT INTO student_interactions (user_id, video_id, event_type, timestamp_offset) VALUES (?, ?, ?, ?)";

// Check if connection is still valid after require_once
if (!$conn || $conn->connect_error) {
    // db.php should have exited, but double-check
    error_log("Database connection error post-include."); // Log error
    send_json_response('error', 'Database connection failed.');
}

$stmt = $conn->prepare($sql);

if ($stmt === false) {
    // Log the detailed error for server-side debugging
    error_log("SQL Prepare Error: " . $conn->error);
    // Send a generic error message to the client
    send_json_response('error', 'An error occurred while preparing the interaction log.');
}

// 6. Bind Parameters (using mysqli)
// 'i' for integer, 's' for string
if (!$stmt->bind_param("iisi", $user_id, $video_id, $event_type, $timestamp_offset)) {
    error_log("SQL Bind Param Error: " . $stmt->error);
    $stmt->close(); // Close statement before exiting
    send_json_response('error', 'An error occurred while binding parameters for the interaction log.');
}

// 7. Execute SQL
if (!$stmt->execute()) {
    error_log("SQL Execute Error: " . $stmt->error);
     $stmt->close(); // Close statement before exiting
    send_json_response('error', 'An error occurred while executing the interaction log.');
}

// 8. Handle Results (Check if insertion was successful)
if ($stmt->affected_rows > 0) {
    send_json_response('success', 'Interaction logged successfully.');
} else {
    // This might happen if the exact same interaction was somehow sent twice
    // depending on constraints, or if there was an issue not caught by execute error.
    send_json_response('error', 'Failed to log interaction. No rows affected (or data might already exist).');
}

// 9. Close statement (connection is closed by send_json_response)
$stmt->close();

// Connection is closed within send_json_response or implicitly at script end if response already sent.

?>