<?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);

    include_once 'db_connection.php'; 
    require_once '../files/guardiankey.php';

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

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

    $client_id = !empty($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;
    $type = filter_var($data['type'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $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']);

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

    if ($type === 'gasto' && $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_finances (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' => 'gasto',
            ':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_finances 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 {
        $transaction_date = filter_var($data['transaction_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        if (empty($transaction_date)) {
            throw new Exception('FECHA REQUERIDA');
        }

        $sql = "INSERT INTO finances (client_id, type, description, amount, transaction_date)
                VALUES (:client_id, :type, :description, :amount, :transaction_date)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':client_id' => $client_id,
            ':type' => $type,
            ':description' => $description,
            ':amount' => $amount,
            ':transaction_date' => $transaction_date
        ]);

        $new_transaction_id = $pdo->lastInsertId();
        $stmt_select = $pdo->prepare("
            SELECT f.id, f.type, f.description, f.amount, f.transaction_date, f.client_id, CONCAT(c.first_name, ' ', c.last_name) as client_name
            FROM finances f LEFT JOIN clients c ON f.client_id = c.id
            WHERE f.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;
?>