timer_stop.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. header('Content-Type: application/json');
  3. header('Access-Control-Allow-Origin: *');
  4. header('Access-Control-Allow-Methods: POST');
  5. header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
  6. require_once '../config/database.php';
  7. $database = new Database();
  8. $conn = $database->getConnection();
  9. $data = json_decode(file_get_contents('php://input'), true);
  10. $id = $data['id'] ?? null;
  11. if ($id && is_numeric($id)) {
  12. try {
  13. // Get timer details first
  14. $query = "SELECT start_time FROM timers WHERE id = ? AND end_time IS NULL";
  15. $stmt = $conn->prepare($query);
  16. $stmt->execute([$id]);
  17. $timer = $stmt->fetch(PDO::FETCH_ASSOC);
  18. if ($timer) {
  19. // Update timer with end_time and duration
  20. $end_time = gmdate('Y-m-d H:i:s');
  21. // Calculate duration
  22. $start = new DateTime($timer['start_time']);
  23. $end = new DateTime($end_time);
  24. $duration = $start->diff($end);
  25. $duration_str = $duration->format('%H:%I:%S');
  26. // Update timer
  27. $updateQuery = "UPDATE timers SET end_time = ?, duration = ?, updated_at = ? WHERE id = ?";
  28. $updateStmt = $conn->prepare($updateQuery);
  29. $updateStmt->execute([$end_time, $duration_str, gmdate('Y-m-d H:i:s'), $id]);
  30. echo json_encode(['success' => true, 'message' => 'Timer stopped successfully']);
  31. } else {
  32. echo json_encode(['success' => false, 'message' => 'Timer not found or already stopped']);
  33. }
  34. } catch (Exception $e) {
  35. echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
  36. }
  37. } else {
  38. echo json_encode(['success' => false, 'message' => 'Invalid timer ID']);
  39. }
  40. ?>