<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');

require_once '../config/database.php';

$database = new Database();
$conn = $database->getConnection();

$task_id = $_GET['task_id'] ?? null;
$date = $_GET['date'] ?? null;

try {
    // Simple database query for timer history
    $query = "SELECT t.*, u.first_name, u.last_name, COALESCE(ta.title, 'Ei tehtävää') as task_title
              FROM timers t 
              LEFT JOIN users u ON t.user_id = u.id 
              LEFT JOIN tasks ta ON t.task_id = ta.id 
              ORDER BY t.created_at DESC";
    
    $stmt = $conn->prepare($query);
    $stmt->execute();
    
    $timers = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // Filter by date if provided
        if ($date && $row['start_time']) {
            $timerDate = date('Y-m-d', strtotime($row['start_time']));
            if ($timerDate !== $date) {
                continue;
            }
        }
        
        // Filter by task_id if provided
        if ($task_id && $row['task_id'] != $task_id) {
            continue;
        }
        
        $timers[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $timers]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
