<?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['title']) || empty($data['due_date'])) {
        $response['message'] = 'Título y fecha de vencimiento son obligatorios.';
        echo json_encode($response);
        exit;
    }

    $title = trim($data['title']);
    $description = trim($data['description'] ?? '');
    $clientId = !empty($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;
    $leadId = !empty($data['lead_id']) ? trim($data['lead_id']) : null;
    $dueDate = $data['due_date'];
    $priority = $data['priority'] ?? 'Media';
    $status = $data['status'] ?? 'pending';

    $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;
    }

    try {
        $stmt = $pdo->prepare(
            "INSERT INTO tasks (title, description, client_id, lead_id, client_name, due_date, priority, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
        );
        $stmt->execute([
            $title,
            $description,
            $finalClientId,
            $finalLeadId,
            $combinedClientName,
            $dueDate,
            $priority,
            $status
        ]);

        $lastId = $pdo->lastInsertId();
        $response = ['success' => true, 'message' => 'Tarea agregada con éxito.', 'id' => $lastId];

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

echo json_encode($response);
exit;
?>