<?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;
$task_id = $data['task_id'] ?? null;
$description = $data['description'] ?? '';
$hours = $data['hours'] ?? 0;

if ($id && is_numeric($id)) {
    try {
        // Get timer details first
        $query = "SELECT * FROM timers WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->execute([$id]);
        $timer = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$timer) {
            echo json_encode(['success' => false, 'message' => 'Timer not found']);
            exit;
        }
        
        // If task is provided, move to work_hours table
        if ($task_id) {
            // Calculate end_time if not set (for active timers)
            $end_time = $timer['end_time'] ?: gmdate('Y-m-d H:i:s');
            
            // Use existing WorkHour model for work_hours insertion
            require_once '../models/WorkHour.php';
            $workHour = new WorkHour($conn);
            
            // Set properties on the WorkHour object
            $workHour->task_id = $task_id;
            $workHour->user_id = $timer['user_id'];
            $workHour->date = date('Y-m-d', strtotime($timer['start_time']));
            $workHour->hours = $hours;
            $workHour->description = $description;
            $workHour->rate = null; // Let WorkHour model fetch rate from task/project/customer
            
            $workHourResult = $workHour->create();
            
            if ($workHourResult) {
                // Remove timer from timers table after successful move
                $deleteQuery = "DELETE FROM timers WHERE id = ?";
                $deleteStmt = $conn->prepare($deleteQuery);
                $deleteStmt->execute([$id]);
                
                echo json_encode(['success' => true, 'message' => 'Timer moved to work hours successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to create work hour entry']);
            }
        } else {
            // No task provided, just update timer description
            $updateQuery = "UPDATE timers SET description = ?, updated_at = ? WHERE id = ?";
            $updateStmt = $conn->prepare($updateQuery);
            $updateResult = $updateStmt->execute([$description, gmdate('Y-m-d H:i:s'), $id]);
            
            if ($updateResult) {
                echo json_encode(['success' => true, 'message' => 'Timer updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update timer']);
            }
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => 'Error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid timer ID']);
}
?>
