<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

switch ($action) {
    case 'log_effort':
        $log = $data['log'];
        $userId = $_SESSION['user_id'];
        
        try {
            global $pdo;
            $pdo->beginTransaction();
            
            // Insert Time Log
            $sql = "INSERT INTO task_time_logs (task_id, user_id, task_status_id, hours_spent, comments) VALUES (?, ?, ?, ?, ?)";
            query($sql, [$log['task_id'], $userId, $log['task_status_id'], $log['hours_spent'], $log['comments']]);
            
            // Update Task Status
            $status = fetch("SELECT name FROM task_statuses WHERE id = ?", [$log['task_status_id']])['name'];
            $newStatus = 'Pending';
            if ($status === 'WIP') $newStatus = 'In Progress';
            if ($status === 'COMPLETED') $newStatus = 'Completed';
            
            query("UPDATE tasks SET status = ? WHERE id = ?", [$newStatus, $log['task_id']]);
            
            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Effort logged successfully']);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
