<?php
ob_start(); 
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../../logs/php_errors.log');
    error_reporting(E_ALL);

    require_once __DIR__ . '/../core/api.php';
    global $pdo;

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

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR AL PROCESAR DATOS JSON');
    }
    
    if (!isset($data['type'], $data['description'], $data['amount']) || empty(trim($data['description']))) {
        throw new Exception('DATOS REQUERIDOS FALTANTES');
    }

    $type_es = filter_var($data['type'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $type_en = ($type_es === 'gasto') ? 'expense' : 'income'; // Mapeo a ENUM de DB
    
    $description = filter_var(trim($data['description']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $amount = filter_var($data['amount'], FILTER_VALIDATE_FLOAT);
    $is_recurring = !empty($data['is_recurring']);
    
    $client_id = !empty($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;
    $provider_name = !empty($data['provider_name']) ? filter_var(trim($data['provider_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;

    if ($amount === false) {
        throw new Exception('MONTO INVALIDO');
    }

    // --- CASO 1: TRANSACCIÓN RECURRENTE (Mapeado a 'recurring_transactions') ---
    if ($is_recurring) {
        
        $start_date = filter_var($data['transaction_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $recurrence_day = filter_var($data['recurrence_day_of_month'], FILTER_VALIDATE_INT);
        $end_date = !empty($data['end_date']) ? filter_var($data['end_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;

        if (empty($start_date) || $recurrence_day === false || $recurrence_day < 1 || $recurrence_day > 31) {
            throw new Exception('RECURRENCIA INVALIDA');
        }

        $sql = "INSERT INTO recurring_transactions (client_id, type, description, amount, recurrence_day_of_month, start_date, end_date)
                VALUES (:client_id, :type, :description, :amount, :recurrence_day, :start_date, :end_date)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':client_id' => $client_id,
            ':type' => $type_en,
            ':description' => $description,
            ':amount' => $amount,
            ':recurrence_day' => $recurrence_day,
            ':start_date' => $start_date,
            ':end_date' => $end_date
        ]);
        
        $new_recurring_id = $pdo->lastInsertId();
        
        $stmt_select = $pdo->prepare("
            SELECT rf.id, rf.type, rf.description, rf.amount, rf.recurrence_day_of_month, rf.start_date, rf.end_date, rf.client_id, 
                   CONCAT(c.first_name, ' ', c.last_name) as client_name
            FROM recurring_transactions rf LEFT JOIN clients c ON rf.client_id = c.id
            WHERE rf.id = ?
        ");
        $stmt_select->execute([$new_recurring_id]);
        $new_recurring_expense = $stmt_select->fetch(PDO::FETCH_ASSOC);

        $response['success'] = true;
        $response['message'] = 'GASTO RECURRENTE CREADO';
        $response['recurring_expense'] = $new_recurring_expense;

    } else {
        // --- CASO 2: TRANSACCIÓN NORMAL (Mapeado a 'transactions') ---
        
        $transaction_date = filter_var($data['transaction_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        if (empty($transaction_date)) {
            throw new Exception('FECHA REQUERIDA');
        }

        $sql = "INSERT INTO transactions (client_id, provider_name, transaction_type, description, amount, transaction_date)
                VALUES (:client_id, :provider_name, :transaction_type, :description, :amount, :transaction_date)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':client_id' => $client_id,
            ':provider_name' => $provider_name,
            ':transaction_type' => $type_en, // Usamos ENUM en inglés
            ':description' => $description,
            ':amount' => $amount,
            ':transaction_date' => $transaction_date
        ]);

        $new_transaction_id = $pdo->lastInsertId();
        
        $stmt_select = $pdo->prepare("
            SELECT t.id, t.transaction_type as type, t.description, t.amount, t.transaction_date, t.client_id, t.provider_name, 
                   CONCAT(c.first_name, ' ', c.last_name) as client_name
            FROM transactions t LEFT JOIN clients c ON t.client_id = c.id
            WHERE t.id = ?
        ");
        $stmt_select->execute([$new_transaction_id]);
        $new_transaction = $stmt_select->fetch(PDO::FETCH_ASSOC);

        $response['success'] = true;
        $response['message'] = 'TRANSACCION GUARDADA';
        $response['transaction'] = $new_transaction;
    }

} catch (PDOException $e) {
    error_log("Error PDO en finances-create.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general en finances-create.php: " . $e->getMessage());
    $response['message'] = strtoupper($e->getMessage());
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;