<?php
session_start();
date_default_timezone_set('Asia/Manila'); // Set to your timezone
require_once '../config/database.php';

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

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] != 'student') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$student_id = $_SESSION['user_id'];
$activity_id = isset($_POST['activity_id']) ? intval($_POST['activity_id']) : 0;

if (!$activity_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid activity']);
    exit();
}

$conn = getDBConnection();

// Check if activity has time limit
$check_query = "SELECT time_limit FROM activities WHERE id = ?";
$stmt = $conn->prepare($check_query);
$stmt->bind_param("i", $activity_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo json_encode(['success' => false, 'message' => 'Activity not found']);
    exit();
}

$activity = $result->fetch_assoc();
$stmt->close();

// Only record start time if activity has time limit
if ($activity['time_limit']) {
    // Check if already started
    $attempt_query = "SELECT id FROM activity_attempts WHERE student_id = ? AND activity_id = ?";
    $stmt = $conn->prepare($attempt_query);
    $stmt->bind_param("ii", $student_id, $activity_id);
    $stmt->execute();
    $attempt_result = $stmt->get_result();

    if ($attempt_result->num_rows == 0) {
        // Record start time
        $stmt->close();
        $insert_attempt = $conn->prepare("INSERT INTO activity_attempts (student_id, activity_id, start_time) VALUES (?, ?, NOW())");
        $insert_attempt->bind_param("ii", $student_id, $activity_id);

        if ($insert_attempt->execute()) {
            $insert_attempt->close();
            $conn->close();
            echo json_encode(['success' => true, 'message' => 'Activity started']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to start activity']);
        }
    } else {
        $stmt->close();
        $conn->close();
        echo json_encode(['success' => true, 'message' => 'Activity already started']);
    }
} else {
    $conn->close();
    echo json_encode(['success' => true, 'message' => 'No time limit']);
}
?>
