<?php
header('Content-Type: application/json');
require_once 'db_connection.php';

$response = ['success' => false, 'message' => 'Solicitud no válida.'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        $response['message'] = 'Error al decodificar JSON: ' . json_last_error_msg();
        echo json_encode($response);
        exit;
    }

    if (empty($data['id'])) {
        $response['message'] = 'ID de tarea no proporcionado.';
        echo json_encode($response);
        exit;
    }

    $taskId = $data['id'];

    try {
        $pdo->beginTransaction();

        if (isset($data['status']) && count($data) === 2) { // Only status update
            $status = $data['status'];
            $stmt = $pdo->prepare("UPDATE tasks SET status = ? WHERE id = ?");
            $stmt->execute([$status, $taskId]);
            $response = ['success' => true, 'message' => 'Estado de tarea actualizado con éxito.'];
        } else { // Full update from the edit panel
            $title = $data['title'] ?? null;
            $description = $data['description'] ?? null;
            $clientId = $data['client_id'] ?? null;
            $leadId = $data['lead_id'] ?? null;
            $dueDate = $data['due_date'] ?? null;
            $priority = $data['priority'] ?? 'Media';

            $finalClientId = null;
            $finalLeadId = null;

            if (!empty($clientId)) {
                $finalClientId = $clientId;
            } elseif (!empty($leadId)) {
                $finalLeadId = $leadId;
            }
            
            $clientName = trim($data['client_name'] ?? '');
            $prospectName = trim($data['prospect_name'] ?? '');
            $combinedClientName = $clientName;
            if (empty($combinedClientName) && !empty($prospectName)) {
                $combinedClientName = $prospectName;
            }


            $stmt = $pdo->prepare(
                "UPDATE tasks SET
                    title = ?,
                    description = ?,
                    client_id = ?,
                    lead_id = ?,
                    client_name = ?,
                    due_date = ?,
                    priority = ?
                WHERE id = ?"
            );
            $stmt->execute([
                $title,
                $description,
                $finalClientId,
                $finalLeadId,
                $combinedClientName,
                $dueDate,
                $priority,
                $taskId
            ]);
            $response = ['success' => true, 'message' => 'Tarea actualizada con éxito.'];
        }

        $pdo->commit();

    } catch (PDOException $e) {
        $pdo->rollBack();
        error_log("PDO Error en tasks-update.php: " . $e->getMessage());
        $response = ['success' => false, 'message' => 'Error de Base de Datos: ' . $e->getMessage()];
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("General Error en tasks-update.php: " . $e->getMessage());
        $response = ['success' => false, 'message' => $e->getMessage()];
    }
}

echo json_encode($response);
exit;
?>