<?php
session_start();
require "db.php";

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    exit;
}

$user_id = $_SESSION['user_id'];

// parse data from navigator.sendBeacon
parse_str(file_get_contents("php://input"), $data);

$course_id   = isset($data['course_id']) ? (int)$data['course_id'] : 0;
$time_spent  = isset($data['time_spent']) ? (int)$data['time_spent'] : 0;
$progress    = isset($data['progress']) ? (int)$data['progress'] : 0;

if ($course_id <= 0 || $time_spent <= 0) exit;

// get course name from courses.id
$stmt = $conn->prepare("SELECT title FROM courses WHERE id=? LIMIT 1");
$stmt->bind_param("i", $course_id);
$stmt->execute();
$result = $stmt->get_result();
$course_row = $result->fetch_assoc();
$course_name = $course_row['title'] ?? 'Unknown Course';
$stmt->close();

$today = date('Y-m-d');

$stmt2 = $conn->prepare("
    INSERT INTO study_activity
        (user_id, course_id, course_name, session_date, time_spent, progress, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
    ON DUPLICATE KEY UPDATE
        time_spent = time_spent + VALUES(time_spent),
        progress   = GREATEST(progress, VALUES(progress)),
        updated_at = NOW()
");
$stmt2->bind_param("iissii", $user_id, $course_id, $course_name, $today, $time_spent, $progress);
$stmt2->execute();
$stmt2->close();
