<?php 
declare(strict_types=1);

require_once __DIR__ . '/../core/api.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendJsonResponse(['success' => false, 'message' => 'msg_invalid_method'], 405);
}

$userId = $_SESSION['user_id'] ?? null;
if (!$userId) {
    sendJsonResponse(['success' => false, 'message' => 'msg_session_expired'], 401);
}

// Validar Permiso
if (!is_module_active('dashboard') || !can('dashboard_view')) {
    sendJsonResponse(['success' => false, 'message' => 'msg_access_denied'], 403);
}

$data = readJsonInput();
$taskId = isset($data['id']) ? (int)$data['id'] : 0;

if (!$taskId) {
    sendJsonResponse(['success' => false, 'message' => 'msg_id_required'], 400);
}

try {
    global $pdo;
    $pdo->beginTransaction();

    // 1. Verificamos propiedad de la tarea
    $stmtCheck = $pdo->prepare("SELECT id FROM tasks WHERE id = ? AND user_id = ?");
    $stmtCheck->execute([$taskId, $userId]);
    if (!$stmtCheck->fetch()) {
        $pdo->rollBack();
        sendJsonResponse(['success' => false, 'message' => 'msg_record_not_found_or_access_denied'], 404);
    }

    // 2. Lógica de actualización (Toggle Estado vs Edición Completa)
    if (isset($data['status']) && count($data) <= 3) { // id + status + (optional params)
        // Caso: Actualización rápida de estado (Drag & Drop o Checkbox)
        $status = sanitizeData($data['status']);
        $stmt = $pdo->prepare("UPDATE tasks SET status = ? WHERE id = ? AND user_id = ?");
        $stmt->execute([$status, $taskId, $userId]);
        $msg = 'msg_status_updated';
    } else {
        // Caso: Edición completa
        $title = sanitizeData($data['title']);
        $description = sanitizeData($data['description'] ?? '');
        $dueDate = sanitizeData($data['due_date']);
        $priority = sanitizeData($data['priority'] ?? 'Medium');
        
        $clientId = !empty($data['client_id']) ? (int)$data['client_id'] : null;
        $leadId = !empty($data['lead_id']) ? (int)$data['lead_id'] : null;
        
        $associatedName = null;
        // Recalcular nombre asociado si cambiaron las relaciones
        if ($clientId) {
            $stmtC = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) as name, company FROM clients WHERE id = ? AND user_id = ?");
            $stmtC->execute([$clientId, $userId]);
            $client = $stmtC->fetch(PDO::FETCH_ASSOC);
            if ($client) $associatedName = trim($client['name']) ?: $client['company'];
        } elseif ($leadId) {
            $stmtL = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) as name FROM leads WHERE id = ? AND user_id = ?");
            $stmtL->execute([$leadId, $userId]);
            $lead = $stmtL->fetch(PDO::FETCH_ASSOC);
            if ($lead) $associatedName = trim($lead['name']);
        } else {
             if (!empty($data['client_name'])) $associatedName = sanitizeData($data['client_name']);
        }

        $stmt = $pdo->prepare("
            UPDATE tasks SET
                title = ?,
                description = ?,
                client_id = ?,
                lead_id = ?,
                client_name = ?,
                due_date = ?,
                priority = ?
            WHERE id = ? AND user_id = ?
        ");
        
        $stmt->execute([
            $title,
            $description,
            $clientId,
            $leadId,
            $associatedName,
            $dueDate,
            $priority,
            $taskId,
            $userId
        ]);
        $msg = 'msg_task_updated';
    }

    $pdo->commit();
    sendJsonResponse(['success' => true, 'message' => $msg]);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log("DB Error (tasks-update): " . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => 'msg_error_db'], 500);
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log("Error (tasks-update): " . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => 'msg_error_internal'], 500);
}
?>