<?php
// db/recurring-finances-create.php
ob_start();
error_reporting(0);
ini_set('display_errors', 0);

include_once 'db_connection.php';

$response = [];

try {
    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Error: JSON inválido recibido.');
    }

    if (!isset($data['type'], $data['description'], $data['amount'], $data['recurrence_day_of_month'], $data['start_date'])) {
        throw new Exception('Datos incompletos. Tipo, descripción, monto, día de recurrencia y fecha de inicio son requeridos.');
    }

    $type = $data['type'];
    $description = trim($data['description']);
    $amount = filter_var($data['amount'], FILTER_VALIDATE_FLOAT);
    $recurrence_day_of_month = filter_var($data['recurrence_day_of_month'], FILTER_VALIDATE_INT);
    $start_date = $data['start_date'];
    $end_date = !empty($data['end_date']) ? $data['end_date'] : null;
    $client_id = !empty($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;

    if ($recurrence_day_of_month < 1 || $recurrence_day_of_month > 31) {
        throw new Exception('El día de recurrencia debe ser entre 1 y 31.');
    }

    $sql = "INSERT INTO recurring_finances (type, description, amount, recurrence_day_of_month, start_date, end_date, client_id) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);

    if ($stmt->execute([$type, $description, $amount, $recurrence_day_of_month, $start_date, $end_date, $client_id])) {
        $last_id = $pdo->lastInsertId();
        $response = ['success' => true, 'message' => 'Transacción recurrente agregada con éxito.', 'id' => $last_id];
    } else {
        throw new Exception('Falló la ejecución de la consulta en la base de datos para la transacción recurrente.');
    }

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

ob_end_clean();
header('Content-Type: application/json');
echo json_encode($response);
exit;
?>