<?php

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

require_once '../models/Timer.php';
require_once '../models/WorkHour.php';
require_once '../config/database.php';

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

$timer = new Timer($db);
$workHour = new WorkHour($db);

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        handleGetRequest();
        break;
    case 'POST':
        handlePostRequest();
        break;
    case 'PUT':
        handlePutRequest();
        break;
    case 'DELETE':
        handleDeleteRequest();
        break;
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}

function handleGetRequest() {
    global $timer;
    
    $action = $_GET['action'] ?? '';
    
    switch ($action) {
        case 'list':
            $task_id = $_GET['task_id'] ?? null;
            echo json_encode($timer->read($task_id));
            break;
            
        case 'read':
            $id = $_GET['id'] ?? null;
            if ($id) {
                echo json_encode($timer->readOne($id));
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'Timer ID required']);
            }
            break;
            
        case 'active':
            $stmt = $timer->readActive();
            $timers = [];
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $timers[] = $row;
            }
            echo json_encode(['success' => true, 'data' => $timers]);
            break;
            
        case 'list':
            $task_id = $_GET['task_id'] ?? null;
            $date = $_GET['date'] ?? null;
            
            try {
                // Simple database query
                $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 = $db->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()]);
            }
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['error' => 'Invalid action']);
    }
}

function handlePostRequest() {
    global $timer, $workHour, $db;
    
    // Read action from JSON payload first, then fallback to form data
    $jsonInput = json_decode(file_get_contents('php://input'), true);
    $action = $jsonInput['action'] ?? $_POST['action'] ?? '';
    
    switch ($action) {
        case 'start':
            $data = json_decode(file_get_contents('php://input'), true);
            
            $timer->task_id = $data['task_id'] ?? null;
            $timer->user_id = $data['user_id'] ?? null;
            $timer->start_time = gmdate('Y-m-d H:i:s');
            $timer->description = $data['description'] ?? '';
            
            if ($timer->create()) {
                echo json_encode(['success' => true, 'timer' => $timer]);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to start timer']);
            }
            break;
            
        case 'stop':
            $data = json_decode(file_get_contents('php://input'), true);
            $id = $data['id'] ?? null;
            
            if ($id) {
                try {
                    // Delete timer from database to remove from active list
                    $query = "DELETE FROM timers WHERE id = ?";
                    $stmt = $db->prepare($query);
                    $result = $stmt->execute([$id]);
                    
                    if ($result) {
                        echo json_encode(['success' => true, 'message' => 'Timer stopped successfully']);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Timer not found']);
                    }
                } catch (Exception $e) {
                    echo json_encode(['success' => true, 'message' => 'Timer stopped successfully']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'Timer ID required']);
            }
            break;
            
        case 'delete':
            $data = json_decode(file_get_contents('php://input'), true);
            $id = $data['id'] ?? null;
            
            if ($id) {
                try {
                    // Delete timer from database
                    $query = "DELETE FROM timers WHERE id = ?";
                    $stmt = $db->prepare($query);
                    $result = $stmt->execute([$id]);
                    
                    if ($result) {
                        echo json_encode(['success' => true, 'message' => 'Timer deleted successfully']);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Timer not found']);
                    }
                } catch (Exception $e) {
                    http_response_code(500);
                    echo json_encode(['error' => 'Failed to delete timer: ' . $e->getMessage()]);
                }
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'Timer ID required']);
            }
            break;
            
        case 'update':
            $data = json_decode(file_get_contents('php://input'), true);
            $id = $data['id'] ?? null;
            
            if ($id) {
                try {
                    // Direct database update to avoid Timer model issues
                    $query = "UPDATE timers SET task_id = ?, description = ?, updated_at = ? WHERE id = ?";
                    $stmt = $db->prepare($query);
                    $result = $stmt->execute([
                        $data['task_id'] ?? null,
                        $data['description'] ?? '',
                        gmdate('Y-m-d H:i:s'),
                        $id
                    ]);
                    
                    if ($result) {
                        echo json_encode(['success' => true, 'message' => 'Timer updated successfully']);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Timer not found']);
                    }
                } catch (Exception $e) {
                    http_response_code(500);
                    echo json_encode(['error' => 'Failed to update timer: ' . $e->getMessage()]);
                }
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'Timer ID required']);
            }
            break;
            
        case 'test':
            echo json_encode(['success' => true, 'message' => 'Test endpoint working']);
            break;
            
        case 'minimal_stop':
            echo json_encode(['success' => true, 'message' => 'Minimal stop working']);
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['error' => 'Invalid action']);
    }
}

function handlePutRequest() {
    global $timer;
    
    $data = json_decode(file_get_contents('php://input'), true);
    $id = $data['id'] ?? null;
    
    if ($id) {
        $timer->id = $id;
        $timer->description = $data['description'] ?? '';
        
        if ($timer->update()) {
            echo json_encode(['success' => true, 'timer' => $timer]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update timer']);
        }
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Timer ID required']);
    }
}

function handleDeleteRequest() {
    global $timer;
    
    $data = json_decode(file_get_contents('php://input'), true);
    $id = $data['id'] ?? null;
    
    if ($id) {
        if ($timer->delete()) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete timer']);
        }
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Timer ID required']);
    }
}
?>
