<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
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();

$data = json_decode(file_get_contents('php://input'), true);
$id = $data['id'] ?? null;

if ($id && is_numeric($id)) {
    try {
        // Get timer details first
        $query = "SELECT start_time FROM timers WHERE id = ? AND end_time IS NULL";
        $stmt = $conn->prepare($query);
        $stmt->execute([$id]);
        $timer = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($timer) {
            // Update timer with end_time and duration
            $end_time = gmdate('Y-m-d H:i:s');
            
            // Calculate duration
            $start = new DateTime($timer['start_time']);
            $end = new DateTime($end_time);
            $duration = $start->diff($end);
            $duration_str = $duration->format('%H:%I:%S');
            
            // Update timer
            $updateQuery = "UPDATE timers SET end_time = ?, duration = ?, updated_at = ? WHERE id = ?";
            $updateStmt = $conn->prepare($updateQuery);
            $updateStmt->execute([$end_time, $duration_str, gmdate('Y-m-d H:i:s'), $id]);
            
            echo json_encode(['success' => true, 'message' => 'Timer stopped successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Timer not found or already stopped']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid timer ID']);
}
?>
