<?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'], $data['recurrence_day_of_month'], $data['start_date'])) {
        throw new Exception('DATOS INCOMPLETOS');
    }

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

    if ($amount === false) throw new Exception('MONTO INVALIDO');
    if ($recurrence_day_of_month === false || $recurrence_day_of_month < 1 || $recurrence_day_of_month > 31) {
        throw new Exception('DIA DE RECURRENCIA INVALIDO');
    }

    $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();
        $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([$last_id]);
        $new_recurring_expense = $stmt_select->fetch(PDO::FETCH_ASSOC);

        $response['success'] = true;
        $response['message'] = 'TRANSACCION RECURRENTE CREADA';
        $response['recurring_expense'] = $new_recurring_expense; 

    } else {
        throw new Exception('FALLO LA EJECUCION DE INSERCION');
    }

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

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